2. Tabelle da MySQL a PHP
Dichiariamo e definiamo la nostra nuova classe, che servirà a mantenere la tabella risultante dalla query MySQL, il più possibile simile al suo stato naturale.
Iniziamo con la dichiarazione dei 3 attributi ...
<?php
class MySQLTable
{
private $righe;
private $colonne;
private $tabella; // Array associativoAndiamo avanti col costruttore, che prenderà come parametro direttamente il valore ritornato dalla query.
// --- Costruttore di MySQLTable ---
function MySQLTable($sql_result)
{
$this->righe = @mysql_num_rows($sql_result);
if (!$this->righe) // Se la query non ha prodotto alcun risultato
{
$this->colonne = 0;
$this->tabella = null;
return; // Assegnata la tabella a NULL esce dalla funzione di costruzione
}
$this->tabella = array();
/* Usiamo il parametro MYSQL_ASSOC per poter accedere all'Array col
nome del campo, così come è nella tabella MySQL */
while ($tmp = @mysql_fetch_array($sql_result, MYSQL_ASSOC))
array_push($this->tabella, $tmp);
$this->colonne = count($this->tabella[0]);
}Di seguito definiamo i 6 metodi della classe, rispettivamente :
|
// --- Metodi di MySQLTable ---
public function cols()
{ return $this->colonne; }
public function rows()
{ return $this->righe; }
public function row($row)
{
if ($this->righe > $row)
return $this->tabella[$row];
else
return null;
}
public function rowAndField($row, $field)
{
if ($this->righe > 0)
return $this->tabella[$row][$field];
else
return null;
}
public function Field($field)
{ return $this->rowAndField(0, $field); }
public function urlencoded()
{
$urlstring = "";
for ($i = 0; $i < $this->righe; $i )
{
for ($k = 0; $k < $this->colonne; $k )
{
$key = key($this->tabella[$i]);
$urlstring .= $key . "__" . ($i 1) . "=" . $this->tabella[$i][$key] . "&";
next($this->tabella[$i]);
}
}
$urlstring .= "__NROWS=" . $this->righe;
return $urlstring;
}
}
?>Salviamo il file col nome della classe "MySQLTable.php" e andiamo avanti con la scrittura del nostro ultimo oggetto.

