php

Connect Mysql and PHP using mysqli

<?php
    class connection {
        public static function createConnection() {
            $servername = "localhost";
            $username = "mysqlUsername";
            $password = "mysqlPassword";
            $dbname = "dbName";

            $conn = new mysqli($servername, $username, $password, $dbname);
            if ($conn->connect_error) {
                die("Connection failed: " . $conn->connect_error);
                return "connection failed";
            } else {
                return $conn;
            }
        }
    }

    //TO CREATE CONNECTION CALL
    $conn = connection::createConnection();
?>

If you are using PHP in your project and want to connect to the Mysql database using mysqli you can use this code snippet. This will return the connection object after creating a connection with the database.

Here, we have created a class in PHP named connection and created a static function 'createConnection' (We do not need to create a new class instance to call the static function). So the function can be called directly.

If the connection is created successfully then it will return the connection object '$conn' or it will return 'connection failed' message if the connection could not be created.

Was this helpful?