How to check the connection to MySQL in PHP

Snippet

The easiest way to check mysql connection is to use the mysqli class:

downloadcopy
<?php
$servername   = "127.0.0.1";
$database = "test_db";
$username = "test";
$password = "F2fdsf3o39qc";
$port = 3306;

// Create connection
$conn = new mysqli($servername, $username, $password, $database, $port);
// uncomment this if you need to connect via socket
//$conn = new mysqli('localhost', $username, $password, $database, NULL, '/run/mysqld/mysqld.sock');`
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>