0

Connecting to the database

September 19, 2022
Share

After creating our database and table in the previous section, we need to connect our project files to this database. To do that, we use the mysqli_connect function (this function allows us to connect and work with the database server). It takes four parameters i.e., the server name, the username, the password and finally the database name. For our case, the details are localhost for server name, root for user (default user in PHP), password is empty (root user has no password that is why it is left empty) and visitors for our database. Let us create a file called connect.php.

connect.php

<?php


    $server = "localhost";
    $username = "root";
    $password = "";
    $database = "visitors";

    $connect = mysqli_connect($server, $username, $password, $database);

    if(!$connect) {
        die("Connection failed: " . mysqli_connect_error());
    } else {
        echo "Connected successfully.";
    }


?>

mysqli_connect function stored in the $connect variable takes on these 4 details that we supplied in the variables above. The if statement is optional, and it is to help us know if our connection to the database was successful. It means, if the details in the connect variable are not true (in otherwards they are incorrect), just kill the connection, return connection failed with the connection error encountered or else return connected successfully if all details are right.

After confirming that we can connect to the database, you can comment out the else part in the if statement by putting a # at the start of the echo statement (We don’t want it to be returned each time we work with the database. The code in the if statement block can now look like this after the change:

 if(!$connect) {
    die("Connection failed: " . mysqli_connect_error());
 } else {
    #echo "Connected successfully.";
 }

This file will be used in other files when inserting data in the database.