The manual Page
Version française
   
index | glossary | news | downloads | links ]
  PHP
PHP basics
syntax
controle structures
MySQL
Oracle
source code
 
news
glossary
links
downloads
 
credits
contact
 
 
search
 
last update
19/02/2003
Valid HTML 4.0!
Valid CSS!
Hit-Parade
Mesurez votre audience


  Connection to a MySQL database

Connection to a MySQL server and the database

PHP is a very convenient and simple tool to use databases.

To use a database, the first thing to do is to connect to this database server:

// Let's prepare the connection
$host = "server_name";
$user = "database_user";
$password = "password";
$bdd = "database_name";

// Connecting...
mysql_connect($host, $user, $password) or die ("Cannot connect
to the database server");

Last step before being able to query the database: connect to the database itself (it is different from the database server: a database server may be used to access several databases):

mysql_select_db($bdd) or die ("Cannot connect to the database");

From now on, it is possible to query the database using the mysql_query and a SQL query:

$result = mysql_query("SELECT * FROM table");

while ($ligne=mysql_fetch_row($result)) {
	...
}

When we have finished to use the database, we must close the connection with the server:

mysql_close();

The mysql_query function

This function is used to make SQL queries to a MySQL database. The prototype for this function is this one:

int mysql_query (string query [, int link_identifier])

This function returns true or false depending on whether the query has succeeded or not.

The link_identifier argument may be used to specify the database on which we want to make the query. If this parameter is not used, PHP uses the last contacted database. Usually, we just have to use a single database, so this argument is most of the time useless, as shown in the example above.

Usually, this function is used with mysql_fetch_row or mysql_fetch_array to get the result of the SQL query row after row in an array:

$result = mysql_query("select * from table");

while ($ligne=mysql_fetch_row($result)) {
	$surname = $ligne[0];
	$name = $ligne[1];
	echo "$surname  $name";
	...
}

Useful functions

name description
mysql_connect used to connected to a MySQL server
mysql_select_db used to connect to a database
mysql_query performs the SQL query on a given database
mysql_close close the connection to a database server
mysql_fetch_row gets the result of the query row after row in an enumerated array
mysql_fetch_array gets the result of the query row after row in an associative array
mysql_num_rows returns the number of rows of the result
mysql_data_seek moves the internal pointer of a MySQL result to a given position

Reference

The MySQL section of php.net

printable format printable format



Copyright © 2000-2002 themanualpage.org - This site is submissive to the terms of the GNU GPL and FDL licences.