santho santho - 4 months ago 14
PHP Question

Connecting my MYSQL database in php

I have my php 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. Anyone has some suggestion?

Answer

mysqli_connect("","username" ,"password","databasename");//Server name cannot be NULL

use loaclhost for server name(In Loacl)

<?php
    $con = mysqli_connect("localhost","username" ,"password","databasename");

    if (mysqli_connect_errno())
    {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
?>

Or can use MySQLi Procedural

<?php
    $servername = "localhost";
    $username = "username";
    $password = "password";

    // Create connection
    $con = mysqli_connect($servername, $username, $password);

    // Check connection
    if (!$con) {
        die("Connection failed: " . mysqli_connect_error());
    }
    echo "Connected successfully";
?>

EDIT 01

$servername = "localhost";
$username = "root";
$password = "";