MySQL Extension Übersichtsbeispiel

Folgendes einfache Beispiel zeigt Ihnen, wie Sie sich mit einer MySQL-Datenbank verbinden, eine Anfrage ausführen, die Ergebnisse ausgeben und die Verbindung wieder trennen.

Beispiel #1 MySQL-Erweiterung: ein Überblicks-Beispiel

<?php
// Verbindung aufbauen, auswählen einer Datenbank
$link = mysql_connect("mysql_host", "mysql_user", "mysql_password")
or die(
"Keine Verbindung möglich: " . mysql_error());
echo
"Verbindung zum Datenbankserver erfolgreich";
mysql_select_db("Meine_Datenbank") or die("Auswahl der Datenbank fehlgeschlagen");

// Ausführen einer SQL-Anfrage
$query = "SELECT * FROM Meine_Tabelle";
$result = mysql_query($query) or die("Anfrage fehlgeschlagen: " . mysql_error());

// Ausgabe der Ergebnisse in HTML
echo "<table>\n";
while (
$line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo
"\t<tr>\n";
foreach (
$line as $col_value) {
echo
"\t\t<td>$col_value</td>\n";
}
echo
"\t</tr>\n";
}
echo
"</table>\n";

// Freigeben des Resultsets
mysql_free_result($result);

// Schließen der Verbinung
mysql_close($link);
?>

add a note

User Contributed Notes 1 note

up
-30
zjrwjzzz at 163 dot com
9 years ago
Be aware that if you are trying to foreach the associative array returned by mysql_fetch_array() with MYSQL_ASSOC or mysql_fetch_assoc(), you have to ensure the return value that is used in foreach structure is exactly a array rather than a FALSE value.

Or you might encounter the warning below:
Warning: Invalid argument supplied for foreach()

Here is an example (assume that $result have already stored the return value from mysql_query()):

If you have some block of code like:

<?php

// Printing results in HTML
echo "<table>\n";
while (
$line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo
"\t<tr>\n";
foreach (
$line as $col_value) {
echo
"\t\t<td>$col_value</td>\n";
}
echo
"\t</tr>\n";
}
echo
"</table>\n";

?>

If this is the case, you should use the code below instead:

<?php

// Check ahead, before using it
if (mysql_num_rows($result) > 0) {
// Printing results in HTML
echo "<table>\n";
while (
$line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo
"\t<tr>\n";
foreach (
$line as $col_value) {
echo
"\t\t<td>$col_value</td>\n";
}
echo
"\t</tr>\n";
}
echo
"</table>\n";
}

?>
To Top