How to Connect Database with PHP

With PHP, you can connect to and make changes in the databases. The data in a MySQL database are stored in tables. A table is a collection of related data, and it consists of columns and rows. Databases are useful for storing information categorically.

For example, a company may have a database with the following tables - Employees, Products, Customers, Orders.

MySQL Connect

Before you can access the MySQL database, you need to connect to the server. There are four steps:

  1. Get Server Name, Username, Password
  2. Create connection
  3. Check for connection - successful or not
  4. Close connection

1. Get Server Name, Username, Password

First, you need servername, username and password.

$servername = "localhost";
$username = "username";
$password = "password";

2. Create Connection

mysqli_connect() is used to open a new connection to the database.

// Create connection
$conn = mysqli_connect($servername, $username, $password);

3. Check connection

The program will check the connection and display the status of the connection.

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
echo "Connected successfully";

The die() function prints a message and exits the current script. The mysqli_connect_error() returns an error description (if any error is there) from the last connection error.

4. Close the connection

The connection will be closed automatically when the script ends. To close the connection before, use the following:



Star InactiveStar InactiveStar InactiveStar InactiveStar Inactive