Mysql
 sql >> Database >  >> RDS >> Mysql

Come usare mysqli_query() in PHP?

Devo ammettere, mysqli_query() l'immissione manuale non contiene un esempio chiaro su come recuperare più righe. Può essere perché la routine è così di routine, nota alla gente di PHP da decenni:

$result = $link->query("DESCRIBE students");
while ($row = $result->fetch_assoc()) {
    // to print all columns automatically:
    foreach ($row as $value) {
        echo "<td>$value</td>";
        // OR to print each column separately:
        echo "<td>",$row['Field'],"</td><td>",$row['Type'],"</td>\n";
    }
}

Nel caso in cui desideri stampare i titoli delle colonne, devi prima selezionare i tuoi dati in un array nidificato e quindi utilizzare i tasti della prima riga:

// getting all the rows from the query
// note that handy feature of OOP syntax
$data = $link->query("DESC students")->fetch_all(MYSQLI_ASSOC);
// getting keys from the first row
$header = array_keys(reset($data));
// printing them
foreach ($header as $value) {
    echo "<td>$value</td>";
}
// finally printing the data
foreach ($data as $row) {
    foreach ($row as $value) {
        echo "<td>$value</td>";
    }
}

Alcuni host potrebbero non avere il supporto per fetch_all() funzione. In tal caso, compila il $data array nel solito modo:

$data = [];
$result = $link->query("DESC students");
while ($row = $result->fetch_assoc())
{
    $data[] = $row;
}

Devo aggiungere due note importanti.

  1. Devi configurare mysqli per generare automaticamente errori invece di controllarli manualmente per ogni istruzione mysqli. Per farlo, aggiungi questa riga prima mysqli_connect() :

     mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    
  2. La nota più importante: a differenza di mysql_query() , mysqli_query() ha un uso molto limitato. Puoi utilizzare questa funzione solo se non verranno utilizzate variabili nella query. Se verrà utilizzata una variabile PHP, non dovresti mai usare mysqli_query() , ma attenersi sempre alle dichiarazioni preparate , in questo modo:

     $stmt = $mysqli->prepare("SELECT * FROM students WHERE class=?");
     $stmt->bind_param('i', $class);
     $stmt->execute();
     $data = $stmt->get_result()->fetch_all();
    

È un po' prolisso, devo ammettere. Per ridurre la quantità di codice è possibile utilizzare PDO o adottare una semplice funzione di supporto per svolgere tutte le attività di preparazione/associazione/esecuzione all'interno di:

$sql = "SELECT * FROM students WHERE class=?";
$data = prepared_select($mysqli, $sql, [$class])->fetch_all();