Working with MySQL in PHP

Photo by Alexander Andrews on Unsplash

Working with MySQL in PHP

MySQL Dec 27, 2022

What does database work look like?

A typical DBMS process in a PHP script consists of several steps:

  1. Establish a connection to the DBMS server by passing the necessary parameters: address, login, password.
  2. Make sure that the connection was successful: the DBMS server is available, the login and password are correct, and so on.
  3. Form a correct SQL query (for example, to read data from a table).
  4. Verify that the request was completed successfully.
  5. Get the result from the DBMS as an array of records.
  6. Use the resulting records in your script (for example, show them in a table).

mysqli connect function: connect to MySQL

Before you start working with data inside MySQL, you need to open a connection to the DBMS server. In PHP, this is done using the standard mysqli_connect(). The function returns a result — a connection resource. This resource is used for all of the following MySQL operations.

But in order to connect to the server, you need to know at least three parameters:

  • DBMS server address;
  • Login;
  • Password.

If you followed the standard MySQL installation procedure or are using OpenServer, then the server address will be localhost, and the login will be root. When using OpenServer, the connection password is an empty string ‘’, and when installing MySQL yourself, you set the password in one of the steps of the installation wizard.

The basic function syntax is mysqli_connect():

mysqli_connect(<server address>, <username>, <password>, <database name>);

Connection test

The first thing to do after connecting to the DBMS is to check that it was successful. This check is needed to exclude an error when connecting to the database. Invalid connection options, misconfiguration, or high load will cause MySQL to reject new connections. All of these situations will result in a connection failure, so the programmer should verify that the connection to the server was successful before proceeding with the following steps.

The MySQL connection is established once in the script and then used for all database queries.

The result of the function execution mysqli_connect()will be a value of a special type - a resource. If the connection to MySQL failed, then the function mysqli_connect()will return a boolean value of type "false" instead of a resource - false. It is good practice to always check the result of this function and compare it to false.

Connecting to MySQL and checking for errors:

<?php
$link = mysqli_connect("localhost", "root", "");

if ($link == false){
    print("Error: Unable to connect to MySQL " . mysqli_connect_error());
}
else {
    print("Connection established successfully");
}
?>

The function mysqli_connect_error()simply returns a textual description of the latest MySQL error.

Tags

Anurag Deep

Logical by Mind, Creative by Heart