Connect PHP to MySQL

To access the data stored in a MySQL database, you should first connect to MySQL database. There are two ways to connect PHP to MySQL database.

Connect PHP to MySQL

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";
?>

Share Tweet Send
Loading...
You've successfully subscribed to Geekinsta
Great! Next, complete checkout for full access to Geekinsta
Welcome back! You've successfully signed in
Success! Your account is fully activated, you now have access to all content.