To access the data stored in a MySQL database, you should first connect to the MySQL database server. There are ways to connect PHP to MySQL database.
- mysqli – (i stands for improved)
- PDO – PHP Data Objects.
In this article, we are using mysqli
extension because it has several benefits over PDO when using MySQL database.
Syntax
$conn_name=new mysqli("servername", "username","password", "database_name");
Specify the database_name
only if you want to use a default MySQL database.
Connect PHP to MySQL – Object Oriented
<?php
//server=localhost, username=root and password=""
$conn = new mysqli("localhost", "root", "");
if ($conn->connect_error)
{
//displaying the connection error
die($conn->connect_error);
}
echo "Connected successfully";
//closing the connection
mysqli_close($conn);
?>
Connect PHP to MySQL – Procedural
<?php
//server=localhost, username=root and password=""
$conn = mysqli_connect("localhost", "root", "");
if (!$conn)
{
//displaying the connection error
die(mysqli_connect_error());
}
echo "Connected successfully";
?>
Subscribe
Join the newsletter to get the latest updates.