Connect to MySql and select database using PHP

The following code is an example of how to connect to a mysql server and select a database to query. We should always free up resources you don’t need anymore i.e make sure that mysql_close() executes at the end. This makes your code more efficient and reduces the possibility of errors.

<?php
$DB_HOST = "localhost";
$DB_NAME = "db";
$DB_USER = "user";
$DB_PASSWORD = "pass";
$con = mysql_connect($DB_HOST, $DB_USER, $DB_PASSWORD);
if (!$con)
{
  die('Could not connect: ' . mysql_error());
}
mysql_select_db($DB_NAME , $con);
mysql_close($con);
?>

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.