How to Connect PHP with MySQL Database

Connecting PHP with a MySQL database allows you to store, retrieve, and manage data easily for your web application.

Follow the steps below to connect PHP with MySQL:

1.Create a database

First, create a database using PHPMyAdmin or the MySQL command line.

Example:

Database name: testdb

2. Connect to Database

To connect to a database using procedural style, use mysqli_connect().

 

<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "testdb";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>

3. Connect to Database (Object-Oriented Style)

You can also connect using object-oriented style with new mysqli().

<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "testdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

4. Close the Database Connection

To close the connection use

<?php
$conn->close();
?>

Summary

PHP allows you to connect to MySQL easily using either procedural or object-oriented methods. Always check the connection and close it after your work to save server resources.

Leave a Reply