Connect to your MySql Database with PHP

First thing to do is to create a new php page. Call it db.php and save it this will be the way you connect to the database through this file so that you only need to write this code once.
Paste this code into your new file and save it. You will have to change the username and password as well as the yourdatabaseName. See below for details.

<?php//connect to the DB
$con = mysql_connect("localhost","username","password");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
 
mysql_select_db("yourdatabaseName", $con);
?>

To explain.

$con = mysql_connect("localhost","name","password");

Most of the time “localhost” remains unchanged. User name is changed to the username of the database and Password is the password you gave to the database. $con is the variable that is created from the connection. You do not need to change this.

if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

This code reads if not connected tell me be printing ‘Could not connect’ … and the error from that is generated from mysql.
NB.The exclamation mark (!) means not.

mysql_select_db("yourdatabaseName", $con);

Otherwise connect to the databse named ‘yourdatabaseName’.

Once you have made your changes save the file.

On any page you need to connect to the database call the db.php with the code.

 <?php 
include_once ('includes/db.php');
?>

I have my db.php in an includes folder which just keeps things nice and neat. In this folder I would also keep my header.php, footer.php, config.php, functions.php and any other files that need to be referred to regularly.

It is best practice to terminate your connection to the database, so at the end of the page that you have made a connection to the database put this little line in.

<?php
mysql_close($con); 
?>

This uses a function to end the connection to the database.

0 Be the first to like this.