downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

Fonctions MySQL> <Exemples
[edit] Last updated: Fri, 25 May 2012

view this page in

Exemple avec l'extension MySQL

Cet exemple simple montre comment se connecter, exécuter une requête, lire les informations obtenues et se déconnecter d'une base de données MySQL.

Exemple #1 Exemple de présentation de l'extension MySQL

<?php
// Connexion et sélection de la base
$link mysql_connect('mysql_host''mysql_user''mysql_password')
    or die(
'Impossible de se connecter : ' mysql_error());
echo 
'Connected successfully';
mysql_select_db('my_database') or die('Impossible de sélectionner la base de données');

// Exécution des requêtes SQL
$query 'SELECT * FROM my_table';
$result mysql_query($query) or die('Échec de la requête : ' mysql_error());

// Affichage des résultats en HTML
echo "<table>\n";
while (
$line mysql_fetch_array($resultMYSQL_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";

// Libération des résultats
mysql_free_result($result);

// Fermeture de la connexion
mysql_close($link);
?>



add a note add a note User Contributed Notes Exemple avec l'extension MySQL
Sz.abi 19-Feb-2009 03:26
You might want to do something like this to output the column names as well:

<?php
echo "<table border=\"1\">\n";
$line = mysql_fetch_array($result, MYSQL_ASSOC);
    echo
"\t<tr>\n";
        echo
"\t\t<th>#</th>\n";
    foreach (
array_keys($line) as $col_value) {
        echo
"\t\t<th>$col_value</th>\n";
    }
    echo
"\t</tr>\n";
$i=0;
do  {
    echo
"\t<tr>\n";
   
$i++;
    echo
"\t\t<th>$i</th>\n";
    foreach (
$line as $col_value) {
        echo
"\t\t<td>$col_value</td>\n";
    }
    echo
"\t</tr>\n";
}while (
$line = mysql_fetch_array($result, MYSQL_ASSOC));
echo
"</table>\n";
?>

(Ok, here I also added line numbers; the main point of this post is using array_keys(...) to display the column names, and using a do {...} while (...); construct to read the first line only once).

 
show source | credits | stats | sitemap | contact | advertising | mirror sites