October 9, 2012 / IST / Database, How-to Guides, Language, Web Development.

MySQL and PHP are two technologies used by many web developers. Connecting to MySQL from PHP is easy and when we consider that both PHP and MySQL are free technologies, the pair sounds like winning choice. This article shows how to connect to MySQL with PHP.

The PHP script below simply connects to a MySQL database and then immediately closes the connection. Of course you will want to do more than that – reading, updating, inserting and deleting data, but once you are connected to the db, these tasks are easy.

<?php
$password = "";
$hostname = "localhost";
$database = "";

$conn = mysql_connect($hostname, $username, $password) 
	or die("Connecting to MySQL failed");

mysql_close($conn);

?>

Now that you have connected to the MySQL server from your PHP script, how do you select which database to work with (there can be more than one database on the same MySQL server)? Here is how to select a MySQL database to work with, from PHP:

<?php
$password = "";
$hostname = "localhost";
$database = "";

$conn = mysql_connect($hostname, $username, $password) 
	or die("Connecting to MySQL failed");

mysql_select_db($database, $conn)
	or die("Selecting MySQL database failed");

mysql_close($conn);

?>

Now that we have selected a MySQL database, we can retrieve some data from it and send it back to the browser from our PHP script:

<?php
$password = "";
$hostname = "localhost";
$database = "";

$conn = mysql_connect($hostname, $username, $password) 
	or die("Connecting to MySQL failed");

mysql_select_db($database, $conn)
	or die("Selecting MySQL database failed");

$sSQL =  "SELECT FirstName, LastName FROM Users";
$result = mysql_query($sSQL, $conn);

while($row = mysql_fetch_object($result)) { 
	echo $row->FirstName . " " . $row->LastName . "<br>";
}

mysql_close($conn);

?>

In the PHP script above we are connecting to MySQL database, selecting data with mysql_query and printing it to the browser.