php mysql database connectivity

Connect with mysql database using php script.

Database connectivity is one of the most important part of php, because this is the first step we have to do whenever we are working with database handling in php.

How to connect?

To connect with mysql database php provides us a predefined function known as mysqli_connect(), So this function is the foundation of php mysql database connectivity because it allows us to get connect with database. mysqli_connect() have four parameters , so we need to fill them with their respective fields.

Syntax.

<?php
mysqli_connect('host_name','user_name','password','database_name');
?>

In above example as you can see there are four parameters in mysqli_connect() function. The first parameter is used to contain host name – by default it is localhost, second parameter is used to contain username – by default it is root, third parameter is used to contain password – by default it is none, the fourth and last parameter is used to contain database name by which we want to connect our web page.

Example.

In my case i have a database named as students, so i want to connect with that database.

<?php
//creating connection.
$myconn = mysqli_connect('localhost','root','','students');
//Testing connection.
if(!$myconn)
{
die('Error while connecting..'.mysqli_connect_error());
}
else
{
echo "Successfully connected to database...";
}
?>

Output.

Successfully connected to database…

As you can see in above example we are using an user defined variable $myconn that is containing the result of mysqli_connect() function, after that we are checking that if(!(not)$myconn), means if this is not happen, then show an error message or else show successful connection. You can also use if($myconn == true) then show successful message or else show error message.

Connecting using user defined variables.

There is another vary good way to establish a database connection, so here we are going to create some variables, after initializing the variable we are going to pass them in parameters of mysqli_connect() function.

<?php
$hostname = "localhost";
$username = "root";
$password = "";
$database = "students";

$myconn = mysqli_connect($hostname,$username,$password,$database);
if(!$myconn)
{
die('Error while connecting..'.mysqli_connect_error());
}
else
{
echo "Successfully connected to database...";
}
?>

Output.

Successfully connected to database…