phpmysqlmysqli

How to connect to MySQL database in PHP using mysqli extension?


I have code like this to connect my server database:

<?php

$con = mysqli_connect("", "username", "password", "databasename");
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

But it displayed "Failed to connect to MySQL", what is wrong with this code? First time I am trying it in web server, whereas my localhost worked perfectly.


Solution

  • Server name cannot be empty. Use localhost if MySQL installed locally

    <?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "test";
    
    // Create connection
    $con = mysqli_connect($servername, $username, $password, $dbname);