ربط PHP بـ MySQL

Free MySQL databases are usually used through PHP.

Connecting to a MySQL Database

Before you can access and process data in a database, you must create a connection to the database.

In PHP, this task is completed through the mysql_connect() function.

Syntax

mysql_connect(servername,username,password);
Parameter Description
servername Optional. Specifies the server to be connected to. The default is "localhost:3306".
username Optional. Specifies the username used for login. The default value is the name of the user owning the server process.
password Optional. Specifies the password used for login. The default is "".

Note:Although there are other parameters, the most important ones are listed above. Please visit the CodeW3C.com provided PHP MySQL Reference Manualfor more details.

Example

In the following example, we store the connection ($con) in a variable that will be used later in the script. If the connection fails, the 'die' part will be executed:

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
// some code
?>

Close Connection

When the script ends, the connection will be closed. If you need to close the connection early, please use the mysql_close() function.

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
// some code
mysql_close($con);
?>