In PHP, if you want to manipulate the data stored in the table of MySQL database, first the database has to be connected. The table’s data cannot be accessed until the database connection is successfully established.
Database connect of PHP to MySQL is done in two ways.
1.Using MySQLi
2.Using PDO (PHP Data Object)
1.Using MySQLi
MySQLi (MySQL improved) is used to connect most of the database. It supports PHP 5 and its next versions.Mysqli_connect () is the function used to connect the database.
Syntax for mysqli_connect()
mysqli_connect(hostname, username, password, database)
<?php $server = "localhost"; $user = "root"; $password = ""; $db = "expertstutorial"; $conn = mysqli_connect($server, $user, $password, $db); if($conn){ echo "Connected successfully."; } else{ echo mysqli_connect_error(); } ?>
Closing connection using MySQLi
mysqli_close($conn);
2.Using PDO (PHP Data Object)
Syntax for PDO
new PDO("mysql:host=hostname;dbname=databasename", "username", "password");
<?php $server = 'localhost'; $user = 'root'; $password = ''; $db = 'expertstutorial'; try{ $conn = new PDO("mysql:host=$server;dbname=$db", $user, $password); echo "Connected successfully."; } catch(PDOException $e){ echo "Connection failed : " . $e->getMessage(); } ?>
Closing connection in PDO
$conn = null;