Connecting database with PHP

Spread the love

We are having certain PHP functions for connecting database with PHP and using the database for various operations. Let’s see them in details.

mysql_connect():

In PHP we are having mysql_connect() function to connect PHP application with MySql database.

Syntax: connection mysql_connect(<server/host>,<username>,<password>);

In above syntax:

  • <server/host> – it’s a host or server of where your database is running. You can use “localhost” for your database address.
  • <username> – it’s the username of your database. For a database on your local machine, it would be “root” by default.
  • <password> –  It’s the password of your database. It’s optional. If you have not set your database password then you can pass a blank string in place of a password.
  • <connection> – it’s a return type of function, function return connection object if function execute successfully else false if fails.

Let’s create PHP script for connecting the database with PHP, named dbconnection.php.
Add below the line of code as a first step.

 

<?php

$host = 'localhost';
$username = 'root';
$password = '';

$con = mysql_connect($host, $username, $password);

if(!$con)
{
die("Error connecting to server - ".mysql_error());
}
else
{
echo "Server conected sucessfully.";
}
?>

Next step is to select a database on which you want to work.

Selecting database:

You can select your required database using function mysql_select_db(). In this step, you actually get connected to your database.

Syantax: boolean mysql_select_db(database_name, connection);

 

In above syntax:

database_name – Its the name of the database you want to work on.

connection – its connection object returned from mysql_connect function.

Example:

Now select your database in above example using mysql_select_db function.

<?php

$host = 'localhost';
$username = 'root';
$password = '';

$con = mysql_connect($host, $username, $password);

if(!$con)
{
die("Error connecting to server - ".mysql_error());
}
else
{
echo "Server connected successfully.";
}

$db = mysql_select_db('company_db', $con);

if($db)
{
echo "Database connected.";
}
else
{
echo "Error connecting database.";
}

...continue
?>

In next chapter, we will see how to insert data in database table employees.


Spread the love

Leave a Comment