Search code snippets, questions, articles...

Connect Mysql and PHP using mysqli

    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;

    $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.

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

Mysql database connection with PHP using mysqli
Was this helpful?
Programming Feeds
Learn something new everyday on Devsheet