Chrome Extension

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();
?>
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool

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.

Search Index Data (The code snippet can also be found with below search text)

Mysql database connection with PHP using mysqli
Was this helpful?
0 Comments
Join Devsheet Ask a Question