PHP MySQL ການເຊື່ອມຕໍ່ຖານຂໍ້ມູນ

Free MySQL databases are usually used through PHP.

Connecting to a MySQL Database

Before you can access and process data in the 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 connect to. The default is "localhost:3306".
username Optional. Specifies the username to log in. The default value is the name of the user owning the server process.
password Optional. Specifies the password to log in. The default is "".

Note:Although there are other parameters, the above lists the most important parameters. Please visit the CodeW3C.com provided PHP MySQL Reference Manual, for more detailed information.

Example

In the following example, we store the connection in a variable ($con) for later use 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);
?>