PHP  
downloads | documentation | faq | getting help | mailing lists | | php.net sites | links 
search for in the  
previousmsqlmysql_affected_rowsnext
Last updated: Tue, 09 Jul 2002
view the printer friendly version or the printer friendly version with notes or change language to English | Brazilian Portuguese | Chinese | Czech | Dutch | Finnish | German | Hungarian | Italian | Japanese | Korean | Polish | Romanian | Russian | Spanish | Swedish | Turkish

LXIII. MySQL

Ces fonctions vous permettent d'acc�der aux bases de donn�es MySQL. Afin de pouvoir les utiliser, vous devez compiler PHP avec le support MySQL, en utilisant l'option --with-mysql. Si vous utilisez cette fonction sans pr�ciser le chemin d'acc�s � la base MySQL, PHP utilisera les librairies clientes MySQL fournies en standard. Les utilisateurs qui font tourner d'autres applications qui utilisent elles-m�mes MySQL (par exemple, PHP 3 et PHP 4 utilis�s comme des modules concurrents apache, ou encore auth-mysql), devraient toujours sp�cifier le chemin jusqu'� MySQL : --with-mysql=/path/to/mysql. Cela va forcer PHP � utiliser les librairies clientes install�es par MySQL et �vitera les conflits.

Plus d'informations sont disponible � .

La documentation de MySQL est disponibles � , ainsi qu'en fran�ais chez .

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 d'introduction

<?php
  $link = mysql_connect("hote_mysql", "login_mysql", "mot_de_passe_mysql")
    or die ("Impossible de se connecter");
  print ("Connexion r�ussie");
  mysql_select_db ("ma_base")
    or die ("Impossible d'acc�der � la base de donn�es");
  $query = "SELECT * FROM ma_table";
  $result = mysql_query ($query)
    or die ("La requ�te a �chou�");
// Affichage du r�sultat au format HTML
  print "<table>\n";
  while($line = mysql_fetch_array($result)){
    print "\t<tr>\n";
    while(list($col_name, $col_value) = each($line)){
      print "\t\t<td>$col_value</td>\n";
    }
    print "\t</tr>\n";
  }
  print "</table>\n";
  mysql_close($link);
?>

Table des mati�res
mysql_affected_rows --  Retourne le nombre de lignes affect�es lors de la derni�re requ�te SQL.
mysql_change_user --  Change le nom de session de l'utilisateur actif.
mysql_character_set_name -- Returns the name of the character set
mysql_close -- Ferme la connexion MySQL.
mysql_connect -- Ouvre une connexion � un serveur MySQL.
mysql_create_db -- Cr�e une base de donn�es MySQL.
mysql_data_seek -- D�place le pointeur interne de r�sultat.
mysql_db_name -- Lit les noms des bases de donn�es
mysql_db_query -- Envoie une requ�te MySQL � un serveur MySQL.
mysql_drop_db -- Efface une base de donn�es MySQL.
mysql_errno --  Retourne le num�ro de message d'erreur de la derni�re op�ration MySQL.
mysql_error --  Retourne le texte associ� avec l'erreur g�n�r�e lors de la derni�re requ�te.
mysql_escape_string --  Prot�ge une cha�ne pour la passer � mysql_query.
mysql_fetch_array --  Retourne une ligne de r�sultat sous la forme d'un tableau associatif.
mysql_fetch_assoc --  Lit une ligne de r�sultats dans un tableau associatif
mysql_fetch_field --  Retourne les donn�es enregistr�es dans une colonne sous forme d'objet.
mysql_fetch_lengths --  Retourne la taille de chaque colonne d'une ligne de r�sultat.
mysql_fetch_object -- Retourne les lignes r�sultats sous la forme d'un objet.
mysql_fetch_row -- Retourne une ligne de r�sultat sous la forme d'un tableau.
mysql_field_flags --  Retourne le s�maphore associ� � la colonne sp�cifi�e dans le r�sultat courant.
mysql_field_len --  Retourne la longueur du champs sp�cifi�.
mysql_field_name --  Retourne le nom d'une colonne
mysql_field_seek --  D�place le pointeur de r�sultat
mysql_field_table --  Retourne le nom de la table o� se trouve une colonne
mysql_field_type --  Retourne le type de la colonne sp�cifi�e dans le r�sultat courant.
mysql_free_result -- Efface le r�sultat de la m�moire.
mysql_get_client_info -- Lit les informations sur le client MySQL
mysql_get_host_info -- Lit les informations sur l'h�te MySQL
mysql_get_proto_info -- Lit les informations sur le protocole MySQL
mysql_get_server_info -- Lit les informations sur le serveur MySQL
mysql_info --  Get information about the most recent query
mysql_insert_id --  Retourne l'identifiant g�n�r� par la derni�re requ�te INSERT.
mysql_list_dbs --  Liste les bases de donn�es disponibles sur le serveur MySQL.
mysql_list_fields -- Liste les champs du r�sultat MySQL.
mysql_list_processes -- List MySQL processes
mysql_list_tables -- Liste les tables d'une base de donn�es.
mysql_num_fields -- Retourne le nombre de champs d'un r�sultat.
mysql_num_rows -- Retourne le nombre de lignes d'un r�sultat.
mysql_pconnect --  Ouvre une connexion persistante � un serveur MySQL.
mysql_ping -- Ping a server connection or reconnect if there is no connection
mysql_query -- Envoie une requ�te SQL � un serveur MySQL.
mysql_real_escape_string --  Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection.
mysql_result -- Retourne un champs d'un r�sultat.
mysql_select_db -- S�lectionne une base de donn�es MySQL.
mysql_stat -- Get current system status
mysql_tablename --  Lit le nom de la table qui contient le champs sp�cifi�.
mysql_thread_id -- Return the current thread ID
mysql_unbuffered_query --  Ex�cute une requ�te SQL sans mobiliser les r�sultats
User Contributed Notes
MySQL
add a note about notes
[email protected]
07-Mar-2000 05:53

A quick way to extract a mysql query result into variables, without using an array:

$result = mysql_query("select model,color,price from cars where id=$id");

extract(mysql_fetch_assoc($result));

Now you have the variables $model, $color, $price. You can ask extract() to prefix it for you, with like extract(stuff,EXTR_PREFIX_ALL,"r"), and right there you have $r_model, $r_color...

If you have to pull multiple rows from the query, e.g. using "while", you have to pull 'em to an array, but still can use extract() to extract them :)

while ($r = mysql_fetch_array($result)) {
extract($r);
...
}

[email protected]
22-Mar-2000 08:38

The easy way to surpress MySQL error messages is to put an "@" in front of the mysql command. For example, @mysql_db_query(whatever).

This also works for any other PHP functions. (ed.)

[email protected]
21-Dec-2000 04:17

Something to Note:

MySQL uses Unix time functions and has no problems with dates until 2069; all 2-digit years are regarded to be in the range 1970 to 2069, which means that if you store 01 in a year column, MySQL treats it as 2001.

15-Feb-2001 06:51
A good place to get beginner's info and some good pointers on using MySQL is:
[email protected]
04-Apr-2001 08:04

Just a note, when using MySQL to output files (ie: a database backup script) if the directory permissions are not set right, it will not create the files AND WILL NOT return an error code. You must have the permissions set right.
[email protected]_spam
01-May-2001 12:37

For one solution to problems with MySQL and special Nordic characters, please see

[email protected]
22-Jun-2001 03:11

The mysql_fetch_[row|object|array] functions return data as type string. Owing to the very flexible nature of php variables, this is normally not relevent, but if you happen to retrieve two integers from a database, then try to compare with bitwise operators, you'll run into trouble, because (19 & 2) == 2, but ("19" & "2") == 0. To remedy this, if you use variables from a database with bitwise operators, use the settype() function to explicitly cast your variables as integers before comparing.
[email protected]
30-Jun-2001 05:24

The mysql_fetch_row function returns an array with numeric indices.

For example, a row from the query:

SELECT bookid,title,author FROM books

would look like:

$record[0]=3
$record[1]="A Farewell To Arms"
$record[2]="Ernest Hemingway"

The mysql_fetch_assoc function returns an array with indices that are the field names, like such:

$record["bookid"]=3
$record["title"]="A Farewell To Arms"
$record["author"]="Ernest Hemingway"

The mysql_fetch_array function returns an array with both kinds of indices, so this array looks like:

$record[0]=3
$record["bookid"]=3
$record[1]="A Farewell To Arms"
$record["title"]="A Farewell To Arms"
$record[2]="Ernest Hemingway"
$record["author"]="Ernest Hemingway"

This is the reason for the "doubled" field output from the example.

Note that the mysql_fetch_array function has an optional parameter where you can specify the indices.

So replacing the call:

mysql_fetch_array($result)

with:

mysql_fetch_array($result,MYSQL_NUM)

would be an identical fix to:

mysql_fetch_row($result)

Hope this helps!

[email protected]
30-Jun-2001 05:41

It looks like the reason for the double vision is so that when you want to use the sql results, you can call the array elements via either indices (e.g. $line[0], $line[1], etc.) or by their database field names (e.g. $line["uid"], $line["pw"], $line["gid"], etc.).

You can see this by changing the example to print $col_name as well as $col_value. Each repeated val shows up with a different key (of course) each time.

[email protected]
13-Jul-2001 07:23

Hi,

The problem with
extract(mysql_fetch_array($result));
is that it actually fetches two arrays, a number index array ($arr[0], $arr[1], $arr[2], ...) and an associative (hash) array, ($arr["field1"], $arr["field2"], $arr["field3"], ...), thus $arr actually contains two sets of data (as you have observed).

If you then try to push out all the data from $arr without explicitly naming those field ids, then you WILL get your data appearing twice.

The full definition for mysql_fetch_array is as follows:
mysql_fetch_array ($result_id, [MYSQL_NUM|MYSQL_ASSOC])
Since MYSQL_NUM is equivalent to mysql_fetch_row, you have found that switching to mysql_fetch_row works fine.
In fact, the only real reason you may want to use mysql_fetch_array is with the MYSQL_ASSOC option, as this allows you to reference the fields in the associative array returned.

[email protected]
23-Jul-2001 06:24

If you're new to this, you really should learn basic SQL before moving on. PHP != SQL. Here's are a few good basic SQL tutorials:

*
*
*

[email protected]
29-Jul-2001 01:41

Since there aren't functions to start and end/rollback transactions, you'll have to use mysql_query("BEGIN"), mysql_query("COMMIT") and mysql_query("ROLLBACK"). These will only work properly on tables that support transactions. You may also wish to roll your own mysql_begin (etc) functions that run the above queries for you.
[email protected]
25-Sep-2001 08:11

Hi, here's a nice little trick to select records in random order from a table in a MySQL database prior to version 3.23

SELECT *, (ItemID/ItemID)*RAND() AS MyRandom FROM Items ORDER BY MyRandom

[[[Editors note:
And just SELECT * FROM foo WHERE bar = RAND() after 3.23
]]]

[email protected]
19-Nov-2001 03:17

ever wanted to know the date a table was last updated? use this:

$info = mysql_fetch_array(mysql_query("show table status from databasename like 'tablename'"));
echo $info["Update_time"];

[email protected]
18-Feb-2002 10:44

I find it the least problematic to simply use the list() construct to assign variables from an array returned from the mysql_fetch_row() & others.

$data = mysql_query("SELECT name, data FROM table");
while(list($t_name, $t_data) = mysql_fetch_row($data)) {
echo "Name: $t_name Data: $t_data\n";
}

It's not too difficult to maintain something like this, since the list() variables mirror the fields being queried. It gets messy when you have more than 10 fields you are working with.

[email protected]
25-Apr-2002 03:23

MySQL transactions

MySQL supports transactions on tables that are of type InnoDB. I have noticed a behaviour which is puzzling me when using transactions.

If I establish two connections within the same PHP page, start a transaction in the first connection and execute an INSERT query in the second one, and rollback the transaction in the first connection, the INSERT query in the second connection is also rolled-back.

I am assuming that a MySQL transaction is not bound by the connection within which it is set up, but rather by the PHP process that sets it up.

This is a very useful "mis-feature" (bug?) because it allows you to create something like this:

class Transaction {
var $dbh;

function Transaction($host, $username, $password) {
$this->dbh = mysql_connect($host, $username, $password);
}

function _Transaction() {
mysql_disconnect($this->dbh);
}

function begin() {
mysql_query("BEGIN", $this->dbh);
}

function rollback() {
mysql_query("ROLLBACK", $this->dbh);
}

function commit() {
mysql_query("COMMIT", $this->dbh);
}
}

which you could use to wrap around transactional statements like this:

$tx =& new Transaction("localhost", "username", "password");
$tx->begin();
$dbh = mysql_connect("localhost", "username", "password");
$result = mysql_query("INSERT ...");
if (!$result) {
$tx->rollback();
} else {
$tx->commit();
}
mysql_disconnect($dbh);
unset($tx);

The benefit of such a Transaction class is that it is generic and can wrap around any of your MySQL statements.

[email protected]
30-May-2002 11:43

I had some difficulties installing PHP with MySQL support on RedHat-7.1, but it works at last. :) Here are a few of the unexpected things I had to do to get it working:
After installing apache, mysql, and php4, I found a php-mysql rpm, since the php4 rpm lacks MySQL support. (I also had to find a few more rpms before this one would install.) Then, I had to make sure and export the path of the library libgcc_s.so (export LD_LIBRARY_PATH=/usr/local/lib) before running the Apache httpd. Otherwise PHP fails to load the MySQL library, which apparently depends on libgcc_s.so, but doesn't give much useful feedback except that the MySQL-specific commands you're using are unrecognized. I hope this saves someone else from going through the hours of hassle it took me to figure it out!

[email protected]
05-Jun-2002 03:04

just a little FYI, when installing PHP from an RPM. In order to get MySql support you need to download the php-mysql*.rpm. If you don't install the php-mysql*.rpm you'll just get the common error: Call to undefined function: mysql_connect().
[email protected]
09-Jun-2002 08:22

To protect your mysql server from long running query which hangs the database

This PHP code basically kills the long running sql process .

I kept this PHP file in cron to run every 15 minues and believe me
it had dramatic performance on my website and my mysql database NEVER HANGED

//################ //

kill_long_query.php
//################ //

set_time_limit(30000);

$result=mysql_query("show processlist");

while ($row=mysql_fetch_array($result))
{
$process_id=$row["Id"];
if (($row["Time"] > 100 ) || ($row["Command"]=="Sleep") )
{
print $row["Id"];
$sql="kill $process_id";
mysql_query($sql);
}

}
//###################//

//###################//

16-Jun-2002 06:38
Regarding transactions, you must use a recent MySQL version which supports InnoDB tables. you should read the mysql manual (the part about Innodb tables, section 7.5) and configure your server to use them.
Some reading about how it works:

(Click where it says Part2, I can't put the direct URL here because it is too long)

Then in PHP you use commands like:

mysql_query("BEGIN");
mysql_query("COMMIT");
mysql_query("ROLLBACK");

You must make sure that you convert your existing tables to innodb or create new ones: CREATE TABLE (...) type=innodb;

add a note about notes
previousmsqlmysql_affected_rowsnext
Last updated: Tue, 09 Jul 2002
show source | credits | stats | mirror sites
Copyright © 2001, 2002 The PHP Group
All rights reserved.
This mirror generously provided by:
Last updated: Sat Aug 31 06:19:44 2002 CEST