LORETTA B. forum

Linguaggi di programmazione => Php e MySql (data base) => Topic aperto da: micdas - Novembre 21, 2010, 22:59:09

Titolo: -1- Gestione completa (o quasi) del DB (Data Base) (MySQL & PHP)
Inserito da: micdas - Novembre 21, 2010, 22:59:09
Queste note nascono dall'esigenza che ho ogni volta debbo lavorare con un DB
Cercherò di mostrare il codice che uso nelle più comuni operazioni da compiere con un DB.

In questa gestione non dobbiamo preoccuparci di creare il nostro DB in quanto ci viene fornito direttamente dal nostro Provider o su esplicita richiesta.
In Altervista normalmente abbiamo a disposizione un unico DB. Su altri spazi ne vengono forniti anche in numero più consistente.
I dati per la connessione vengono forniti al momento dell'attivazione dei DB e ci vengono comunicati tramite E_Mail e su pannello di controllo.
Detto questo possiamo passare subito alla sua gestione.

Quel che riveste una maggior importanza nella gestione del DB è la creazione delle Query ("interrogazione"). Da queste dipende il buon esito di una interrogazione che si fa al DB.
Le query che rivolgiamo ad un DB sono di due tipi:

Per la lettura le Query più frequenti possono essere:

Per la scrittura si istruiscono delle Query che possano

Specie le interrogazioni fatte in lettura possono essere di due tipi:
Per le interrogazioni fatte in scrittura, normalmente, non viene restituito alcun dato

Per non appesantire troppo le pagine che contengono gli script, generalmente, faccio uso di due files esterni che richiamo nelle pagine con la funzione PHP include ()

I files che ho usato in questa esercitazione sono:

Queste sono le variabili che si trovano nel file config_db.php:
Codice: Non sei autorizzato a vedere i links. Registrati o Login
<?php
//    *************************************************
//    dati da cambiare per il collegamento al DB
$Host "indirizzo dell'host";
$User "username";
$Password "password";
$DBName "nome_db";
//    *************************************************

$table "rubrica";
$campi_rubrica = array (
    
"id",
    
"cognome",
    
"nome",
    
"nato",
    
"indirizzo",
    
"cap",
    
"citta",
    
"prov",
    
"tel1",
    
"tel2",
    
"tel3"
);
$campi_gest_date = array (
    
"id",
    
"testo1",
    
"data_serial",
    
"data",
    
"orario",
    
"testo2",
    
"testo3"
);
$nomi_campi = array (
    
"id" => "non inserire",
    
"cognome" => "Cognome",
    
"nome" => "Nome",
    
"nato" => "Data di nascita (formato: gg/mm/aaaa)",
    
"indirizzo" => "Indirizzo",
    
"cap" => "CAP",
    
"citta" => "Citt&agrave;",
    
"prov" => "Prov",
    
"tel1" => "Telefono di casa",
    
"tel2" => "Cellulare",
    
"tel3" => "Fax"
);
$tipi_campi = array (
    
"cognome varchar(100)",
    
"nome varchar(100)",
    
"nato DATE NOT NULL DEFAULT '0000-00-00'",
    
"indirizzo varchar(100)",
    
"cap varchar(10)",
    
"citta varchar(100)",
    
"prov varchar(10)",
    
"tel1 varchar(20)",
    
"tel2 varchar(20)",
    
"tel3 varchar(100)"
);
$request_campi = array (
    
"cognome",
    
"nome"
);
?>


Queste invece sono alcune delle mie funzioni personali, che si trovano nel file function.php e che uso frequentemente in questo tutorial.
Alcune delle funzioni non vengono usate qui ma le ho lasciate solo a scopo illustrativo.
Codice: Non sei autorizzato a vedere i links. Registrati o Login
<?php
function show_tables($Query$pref="") {
    global 
$Host;
    global 
$User;
    global 
$Password;
    global 
$DBName;
    if (!
$link mysql_connect($Host$User$Password)) {
        return 
FALSE;
    }
    if (!
mysql_select_db($DBName$link)) {
        return 
FALSE;
    }
    
$result mysql_query($Query$link);
    if (!
$result) {
        echo 
"errore nella query della funzione<br />\n" $Query "<br />";
        return 
FALSE;
    } else {
        
$tab = array();
        while (
$row mysql_fetch_row($result)) {
            
$tab[] = $row[0];
        }
    }
    
mysql_close ($Link);
    return 
$tab;
}
function 
table_exists($tabella) {
    global 
$Host;
    global 
$User;
    global 
$Password;
    global 
$DBName;
    if (!
$link mysql_connect($Host$User$Password)) {
        return 
FALSE;
    }
    if (!
mysql_select_db($DBName$link)) {
        return 
FALSE;
    }
    
$Query "SELECT * FROM ".$tabella;
    if( 
mysql_query($Query$link)) {
        return 
true;
    } else {
        return 
false;
    }
}
function 
mostra_campi($tabella) {
    global 
$Host;
    global 
$User;
    global 
$Password;
    global 
$DBName;
    
$Link mysql_connect ($Host$User$Password);
    
$fields mysql_list_fields($DBName$tabella$Link);
    
$columns mysql_num_fields($fields);
    for (
$i 0$i $columns$i++) {
        
$field[] = mysql_field_name($fields$i);
    }
    
mysql_close ($Link);
    return 
$field;
}
function 
num_record($query) {
    global 
$Host;
    global 
$User;
    global 
$Password;
    global 
$DBName;
    if (!
$link mysql_connect($Host$User$Password)) {
        return 
FALSE;
    }
    if (!
mysql_select_db($DBName$link)) {
        return 
FALSE;
    }
    
$result mysql_query($query$link);
    if (!
$result) {
        return 
FALSE;
    }
    
$num_rec mysql_num_rows($result);
    
mysql_close ($link);
    return 
$num_rec;
}
function 
execute_query($query) {
    global 
$Host;
    global 
$User;
    global 
$Password;
    global 
$DBName;
    if (!
$link mysql_connect($Host$User$Password)) {
        return 
FALSE;
    }
    if (!
mysql_select_db($DBName$link)) {
        return 
FALSE;
    }
    
$result mysql_query($query$link);
    if (!
$result) {
        echo 
"errore nella query della funzione<br />\n" $query "<br />";
        return 
FALSE;
    }
    
mysql_close ($link);
    return 
TRUE;
}
function 
verify_record($table$nome$cognome$data) {
    global 
$Host;
    global 
$User;
    global 
$Password;
    global 
$DBName;
    
$Query "SELECT * FROM ".$table.
    WHERE nome = '"
.$nome."' 
    AND cognome = '"
.$cognome."' 
    AND nato = '"
.$data."';";
    if (!
$link mysql_connect($Host$User$Password)) {
        die (
'errore nella connessione');
    }
    if (!
mysql_select_db($DBName$link)) {
        die(
'DataBase non trovato');
    }
    
$result mysql_query($Query$link);
    if (!
$result) {
        die (
"errore nella Query");
    }
    
$num_rec mysql_num_rows($result);
    
mysql_close ($link);
    if (
$num_rec != 0) {
    return 
$num_rec;
    } else {
    return 
FALSE;
    }
}
function 
conta_record($tabella) {
    global 
$Host;
    global 
$User;
    global 
$Password;
    global 
$DBName;
    
$Link mysql_connect ($Host$User$Password);
    
$Query "SELECT * FROM ".$tabella;
    if (
mysql_db_query ($DBName$Query$Link)) {
    
$Result mysql_db_query ($DBName$Query$Link);// or die($errore);
    
$num_rec mysql_num_rows($Result);
    }
    
mysql_close($Link);    
    return 
$num_rec;
}
function 
connect_db($tabella$where false) {    
    global 
$Host;
    global 
$User;
    global 
$Password;
    global 
$DBName;
    
$self $_SERVER['PHP_SELF'];
    
$campi mostra_campi($tabella);
    
$campo $campi[0];
    if (isset(
$_REQUEST['campo'])) {
        
$campo $_REQUEST['campo'];
    }
    
$string "";
    
$lemma $_REQUEST['cerca'];
    if (
$lemma != "") {
        
$string "&amp;cerca=".$lemma;
    }
    
$Query "SELECT * FROM ".$tabella;
    if (
$where) {
        
$Query .= $where;
    }
    
$Query .= " ORDER by ".$campo.";";
    if (!
$link mysql_connect($Host$User$Password)) {
        die (
'errore nella connessione');
    }
    if (!
mysql_select_db($DBName$link)) {
        die(
'DataBase non trovato');
    }
    
$result mysql_query($Query$link);
    if (!
$result) {
        echo 
$Query "<br />";
        die (
"errore nella query<br />".mysql_error());
    }
    
$num_rec mysql_num_rows($result);
    if (
$num_rec == 0) {
        echo 
"nessun record nella tabella";
    } else {
    echo 
$num_rec " record trovati in archivio<br />\n";
    echo 
"<table>\n";
    echo 
"<tr>\n";
    echo 
"<th><a href=\"".$self."?campo=".$campi[0].$string."\">ID</a></th>\n";
    echo 
"<th><a href=\"".$self."?campo=".$campi[1].$string."\">Nome</a></th>\n";
    echo 
"<th><a href=\"".$self."?campo=".$campi[3].$string."\">nato</a></th>\n";
    echo 
"<th><a href=\"".$self."?campo=".$campi[4].$string."\">indirizzo</a></th>\n";
    echo 
"<th><a href=\"".$self."?campo=".$campi[6].$string."\">citt&agrave;</a></th>\n";
    echo 
"<th>Telefoni</th>\n";
    echo 
"</tr>\n";
    while (
$row mysql_fetch_array($result)) {
        echo 
"<tr>\n";
        echo 
"<td>" $row['id'] . "</td>\n";
        echo 
"<td>" $row['cognome'] . " ";
        echo 
$row['nome'] . "</td>\n";
        
$data $row['nato'];
        
$timestamp time_serial_da_db($data);
        
$nuova_data date ("d-m-Y",$timestamp);
        echo 
"<td>" $nuova_data "</td>\n";
        echo 
"<td>" $row['indirizzo'] . "</td>\n";
        echo 
"<td>" $row['cap'] . " ";
        echo 
$row['citta'] . " ";
        echo 
$row['prov'] . "</td>\n";
        echo 
"<td>";
        
$tel = array();
        if (
$row['tel1'] != "") {
            
$tel[] = $row['tel1'];
        }
        if (
$row['tel2'] != "") {
            
$tel[] = $row['tel2'];
        }
        if (
$row['tel3'] != "") {
            
$tel[] = $row['tel3'];
        }
        if (
is_array($tel)) {
            
$telefono implode("<br />"$tel);
        }
        echo 
$telefono;
        echo 
"</td>\n";
        echo 
"</tr>\n";
    }
    
mysql_close ($link);
    echo 
"</table>\n";
    }
}
function 
time_serial_da_db($data_letta) {
    
$data_1 str_replace("/""-"$data_letta);
    
$sub explode("-"$data_1);
    
$a $sub[0];
    
$m $sub[1];
    
$g $sub[2];
    
$timestamp_rec mktime(0,0,0,$m,$g,$a);
    return 
$timestamp_rec;
}
function 
time_serial($data_letta) {
    
$data_1 str_replace("/""-"$data_letta);
    
$sub explode("-"$data_1);
    
$g $sub[0];
    
$m $sub[1];
    
$a $sub[2];
    
$timestamp_rec mktime(0,0,0,$m,$g,$a);
    return 
$timestamp_rec;
}
function 
verify_pref($string$pref) {
    
$sub explode("_"$string);
    if (
$sub[0] == $pref) {
        return 
TRUE;
    } else {
        return 
FALSE;
    }
}
?>


Tutto quanto verrà gestito da una sorta di pannello di controllo al quale si farà spesso ritorno tra un'operazione ed un'altra
Codice: Non sei autorizzato a vedere i links. Registrati o Login
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Gestione cerca</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<link href="css/stile.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="container">
    <div id="header">
    <h1>&nbsp;</h1>
    </div>
    <div id="navigation">&nbsp;</div>
    <div id="content">
    <h1>Indice delle funzionalità</h1>
    <h2>i vari metodi per i DB</h2>
    <div align="center">
<table class="table_1">
<tr>
<td rowspan="3">Gestione delle tabelle</td>
<td><a href="crea_tables.php">Crea nuova tabella</a></td>
</tr>
<tr>
<td><a href="cancella_tabella.php">Elimina tabella</a></td>
</tr>
<tr>
<td><a href="show_tables.php">Elenco delle tabelle</a></td>
</tr>
<tr>
<td rowspan="6">Lavoro sui dati</td>
<td><a href="scrivi_form.php">Inserisci Record Manualmente</a></td>
</tr>
<tr>
<td><a href="leggi_file_testo.php">Importa i dati da file di testo</a></td>
</tr>
<tr>
<td><a href="leggi_record.php">Vedi Record</a></td>
</tr>
<tr>
<td><a href="gestione_record.php">Gestione record</a>
(Modifica, Elimina Record</td>
</tr>
<tr>
<td><a href="cerca.php?tabella=rubrica">Ricerche</a></td>
</tr>
<tr>
<td><a href="svuota.php">Svuota tabella</a></td>
</tr>
</table>
<p>&nbsp;</p>
    </div>
    </div>
    <div id="footer">
    <p><a href="../../../index.php">Torna al sito</a></p>
    &nbsp;
    </div>
</div>
</body>
</html>

Ecco. Fin qui è solo l'inizio. Con le prossime pagine inizieremo il tour.

Alla prossima    :bye: