How to create MySQL connection in PHP ?

Mysql is a database which is mostly used in a PHP environment. You can create MySQL connection using PHP code easily. Here you can find the PHP connection code using both drivers MySQLi and MySQL. MySQLi is an improved version of MySQL driver. PHP 7 and later version support MySQLi driver.

MySQLi connection in PHP using MySQLi driver :

$dbName = 'database_name';  // Set database name
$hostaddress = 'localhost'; // Set localhost if database and PHP file on same server or use server address
$username = 'root'; // root is a default username of xampp server in local environment, you can change it.
$password = '';

$conn = mysqli_connect($hostaddress, $username, $password, $dbName);

if(isset($conn)){
echo "Database Connected Successfully!";
} else {
echo "Error in Database Connection!";
}

MySQL connection in PHP using MySQL driver :

$dbName = 'database_name';  // Set database name
$hostaddress = 'localhost'; // Set localhost if database and PHP file on same server or use server address
$username = 'root'; // root is a default username of xampp server in local environment, you can change it.
$password = '';

mysql_connect($hostaddress, $username, $password) or die("<center>Error in Database Connection!".mysql_error()."'</center>");
mysql_select_db($dbName);

PHP Code With Example :

First of all, You will have to install XAMPP Server on local PC –

After successful installation of XAMPP Server (click here to download XAMPP Server), You can open phpMyAdmin using URL http://localhost:80/phpmyadmin.

<?php
$dbName = 'database_name';
$hostaddress = 'localhost';
$username = 'root';
$password = '';
$conn = mysqli_connect($hostaddress, $username, $password, $dbName);
if(isset($conn)){

if(isset($_REQUEST['submitbtn'])){

$sql_insert = "Insert into employee set username = '".$_REQUEST['username']."', password = '".$_REQUEST['userpwd']."'";
$query_insert = mysqli_query($conn, $sql_insert);
echo "Employee details inserted sucesfully!";
}

} else {
echo "Error in Database Connection!";
}
?>

<form method="post" name="uservalue" id="uservalue" action="">
<table width="100%">
<tr>
<td>Username : </td>
<td><input type="text" name="username" id="username" /></td>
</tr>
<tr>
<td>Password : </td>
<td><input type="password" name="userpwd" id="userpwd" /></td>
</tr>
<tr>
<td>&amp;nbsp;</td>
<td><input type="submit" name="submitbtn" id="submitbtn" value="Submit" /></td>
</tr>
</table>
</form>