PHP Tutorials


Connect PHP to a MySQL Database
March 4, 2008, 2:38 am
Filed under: PHP/MySQL

Connect PHP to a MySQL Database
MySQL is the most common database used with PHP.

Connecting PHP to a MySQL Database
You must first connect to a database so you can access and work with data in a database.

 

Syntax (Connect PHP to MySQL):
mysql_connect(servername, username, password);

Example (Connect PHP to MySQL):
In this example, I stored the connection in the $connect variable so we will be using it later and if it failed to connect then the die statement will be executed.

<?php
$connect = mysql_connect(“localhost”,”bryan”,”777”);
if(!$connect)
{
die(“Failed to connect: “ . mysql_error());
}
?>

Closing a connection
As soon as the script ends, the connection will be automatically closed but you can close it by using the mysql_close() function.

Here is an example:

<?php
$connect = mysql_connect(“localhost”,”bryan”,”777”);
if(!$connect)
{
die(“Failed to connect: “ . mysql_error());
}
mysql_close($connect);
?>


No Comments Yet so far
Leave a comment



Leave a comment
Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>