giorno settimanamesegiorno

Sono passati 88 giorni dall'inizio dell'anno che corrispondono a 13 settimane

Arcobaleno, domani sereno



* Chattina

Aggiorna Storia
  • mar: :resistere:
    Febbraio 15, 2022, 19:44:48
  • mar: Non mi ricordavo di essere un global moderator wauuuu Ok Prof ti lascio restaurare in pace!
    Febbraio 15, 2022, 19:43:56
  • mar: :Cartelli70:
    Febbraio 15, 2022, 19:41:14
  • mar: ad cazzum pure qui?
    Febbraio 15, 2022, 19:41:02
  • mar: ciaoooo sono in perlistrazione
    Febbraio 15, 2022, 19:40:44
  • mar: :okkey:
    Febbraio 15, 2022, 19:40:20
  • Loretta/Nina: ciao a tutti
    Ottobre 04, 2021, 19:23:02
  • Loretta/Nina: :tuffarsi:
    Settembre 21, 2021, 07:08:03
  • Loretta/Nina: Buon autunno a tutti
    Settembre 21, 2021, 07:01:35
  • nuvolotta: avventure testuali
    Luglio 06, 2020, 23:26:08
  • _jan_: ...gli ultimo però....!!
    Gennaio 14, 2019, 14:45:09
  • _jan_: vedi gli ultimi post in fondo.
    Novembre 24, 2018, 19:10:00
  • mar: Trovato :Amm9:
    Novembre 24, 2018, 18:57:51
  • mar: Chi cerca trova non vi trovo! :Cartelli2:
    Novembre 24, 2018, 18:57:05
  • mar: Vado a vedere le cartoline!
    Novembre 24, 2018, 18:52:38
  • mar: :Amore145:
    Novembre 24, 2018, 18:52:21
  • mar: :Amore178:
    Novembre 24, 2018, 18:52:07
  • _jan_: Welcome Visitor.  :Party133:
    Novembre 15, 2018, 10:03:24
  • Loretta/Nina: Benvenuto ligi  :Cartelli37:
    Ottobre 09, 2018, 13:19:25
  • nuvolotta: Cucù...  :Amore20:
    Settembre 16, 2018, 01:16:47
  • Loretta/Nina: :Party133:
    Settembre 01, 2018, 17:05:30
  • _jan_: Ciao ai visitors!!
    Settembre 01, 2018, 17:02:31
  • Loretta/Nina: :fischio: :979:
    Agosto 28, 2018, 16:20:48
  • ketty: ah beh, meno male. ora il tempo e' un po' brutto
    Agosto 26, 2018, 13:27:36
  • _jan_: No, no, soqquà. Ci passo ma....... non c'è mai nessuno. Ammiro Nuvolotta, solitaria e presente.
    Agosto 25, 2018, 10:34:41
  • ketty: ma Jan è andato in vacanza? :Cartelli70:
    Agosto 24, 2018, 20:51:59
  • ketty: ciao a tutti.
    Agosto 24, 2018, 20:50:12
  • nuvolotta: :faccina_fiore: ciao ragazzioli/ole...
    Agosto 19, 2018, 23:03:49
  • Loretta/Nina: :ciao: :Party133:
    Agosto 19, 2018, 20:24:28
  • _jan_: :Felici13:
    Agosto 04, 2018, 15:30:40
  • nuvolotta: Ferie... già fatte....
    Agosto 04, 2018, 09:54:58
  • _jan_: Auguri di buon onomastico a tutti gli Alfonso....
    Agosto 01, 2018, 11:10:21
  • _jan_: chiusp per ferie?
    Luglio 30, 2018, 19:50:58
  • _jan_: Buon onomastico a Donatella Seconda........ e la prima? :Shok145:
    Luglio 30, 2018, 06:59:38
  • _jan_: Buon onomastico a tutte le Marta.  :Amore20:
    Luglio 29, 2018, 07:44:31
  • _jan_: Ci sono altre nuove iscritte viste il 26 luglio 2018..... (mica saranno monache)....  :approva:
    Luglio 26, 2018, 18:39:04
  • _jan_: Oggi, 26 luglio 2018, abbiamo una nuova iscritta "Francesca".....Benvenuta Francesca.  :Party133:
    Luglio 26, 2018, 15:49:24
  • _jan_: Buon onomastico anche a tutte le Anna!!! .....
    Luglio 26, 2018, 10:30:21
  • _jan_: Auguri di Buon Onomastico a TUO..... (ogni giorno, credo)..... :sm269:
    Luglio 26, 2018, 10:28:52
  • ketty: ma.... quando è il tuo?
    Luglio 25, 2018, 19:52:19

* Emoticon aggiuntive e link al portale


Autore Topic: -1- Gestione completa (o quasi) del DB (Data Base) (MySQL & PHP)  (Letto 2420 volte)

0 Utenti e 1 Visitatore stanno visualizzando questo topic.

Offline micdas

  • Administrator
  • Hero Member
  • *****
  • Post: 848
  • Sesso: Maschio
    • sito su Excel ed il suo vba
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.

  • Gestione delle tabelle
    • Crea nuova tabella
    • Elimina tabella
    • Elenco delle tabelle
  • Lavoro sui dati
    • Inserisci Record Manualmente
    • Importa i dati da file di testo
    • Vedi Record
    • Gestione record (Modifica, Elimina Record
    • Ricerche
    • Svuota tabella
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:
  • in lettura
  • in scrittura

Per la lettura le Query più frequenti possono essere:
  • lettura delle tabelle presenti in un DB
  • verifica dell'esistenza di una tabella
  • lettura dei campi di una tabella
  • lettura dei record memorizzati in una tabella
  • lettura del numero dei record

Per la scrittura si istruiscono delle Query che possano
  • creare una tabella con relativi campi
  • eliminare una tabella
  • inserire record in una tabella
  • modificare i record
  • eliminare i record

Specie le interrogazioni fatte in lettura possono essere di due tipi:
  • lettura con restituzioni di dati
  • lettura senza restituzione dei dati
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:
  • config_db.php (che contiene le variabili più frequentemente usati)
  • functions.php (che contiene delle mie funzioni personali dove ho scritto codice più frequentemente usato nelle mie pagine di script

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:
« Ultima modifica: Novembre 23, 2010, 23:02:38 da micdas »
E' stupido pensare di non aver bisogno degli altri