2

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.

2
  • Try specifying the hostname in mysqli_connect.
    – Abey
    Jul 13, 2015 at 5:51
  • It's because the host parameter is neither null or set. It's practically empty. So the mysql can't connect now to "".
    – Peter
    Jul 13, 2015 at 6:17

9 Answers 9

3

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 = "";
4
  • i tried MySQLi Procedural, it displays Connection failed: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
    – santho
    Jul 13, 2015 at 6:06
  • 1
    Is your mySQL server running? If it's running, restart your service.
    – Peter
    Jul 13, 2015 at 6:19
  • 1
    I solved it guys, using current server ip address instead of localhost or 127.0.0.1!1
    – santho
    Jul 13, 2015 at 6:23
  • if you use localhost its also same result. Jul 13, 2015 at 6:24
2

To connect to the MySQL database using mysqli you need to execute 3 lines of code. You need to enable error reporting, create instance of mysqli class and set the correct charset.

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'username', 'password', 'dbname', 3307);
$mysqli->set_charset('utf8mb4'); // always set the charset

The parameters in the mysqli constructor are all optional, but most of the time you would want to pass at least 4 of them. In the correct order they are:

  1. MySQL Host. Most of the time it is localhost, but if you connect to a remote host it will be some other IP address. Make sure this does not contain the http protocol part. It should either be an IP address or the URL without protocol.
  2. Username. This is the username of your MySQL user. To connect to the MySQL server you need to have a valid user with the right privileges.
  3. Password.
  4. Database name. This is the MySQL database name you want to connect to.
  5. Port. Most of the time the default port is the correct one, but if you use for example wampserver with MariaDB, you might want to change it to 3307.
  6. Socket name. Specifies the socket or named pipe that should be used.

Unfortunately the charset is not one of these parameters, so you must use a dedicated function to set this very important parameter.

Please beware never to display the connection errors manually. Doing so is completely unnecessary and it will leak your credentials.

On unrelated note: I do not recommend to use MySQLi in a new project. Please consider using PDO, which is overall a much better API for connecting to MySQL.

0
1

Why use mysqli? Just use PDO for safer mysql connection just use:

$hostname='localhost';
$username='root';
$password='';


$dbh = new PDO("mysql:host=$hostname;dbname=dbname",$username,$password);
-1

You should specify hostname

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

If it returns an error like

Failed to connect to MySQL: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock'

Replace localhost with 127.0.0.1.

If still you cant connect check if mysql server is actually running.

service mysqld start

Then, try the one of the following following:

(if you have not set password for mysql)

mysql -u root

if you have set password already

mysql -u root -p
-1
$localhost = "localhost";
    $root = "root";
    $password = "";
    $con = mysql_connect($localhost,$root,$password) or die('Could not connect to database');
    mysql_select_db("db_name",$con);
-2
<?php

$servername="";
$username=""; 
$password="";
$db="";

$conn=mysqli_connect($servername,$username,$password,$db);
//mysql_select_db($db);  
if (!$conn) {
    echo "Error: Unable to connect to MySQL." . PHP_EOL;
    echo "Debugging errno: " . mysqli_connect_errno($conn) . PHP_EOL;
    echo "Debugging error: " . mysqli_connect_error($conn) . PHP_EOL;
    exit;
}
@session_start();

$event_name = $_POST['first_name'];
$first_name = $_POST['last_name'];

$sql = "INSERT INTO customer(first_name, last_name,) VALUES ('$first_name', '$last_name')";

$conn->query($sql);
$lastInsertId = mysqli_insert_id($conn);

?>
-2

A better method is to keep the connection and the login parameters apart.

<?php

class Database{

protected $url;
protected $user;
protected $passw;
protected $db;
protected $connection = null;

public function __construct($url,$user,$passw,$db){
    $this->url = $url;
    $this->user = $user;
    $this->passw = $passw;
    $this->db = $db;
}

public function __destruct() {
    if ($this->connection != null) {
        $this->closeConnection();
    }
}

protected function makeConnection(){
    //Make a connection
    $this->connection = new mysqli($this->url,$this->user,$this->passw,$this->db);
    if ($this->connection->connect_error) {
        echo "FAIL:" . $this->connection->connect_error;
    }
}

protected function closeConnection() {
    //Close the DB connection
    if ($this->connection != null) {
        $this->connection->close();
        $this->connection = null;
    }
}

protected function cleanParameters($p) {
    //prevent SQL injection
    $result = $this->connection->real_escape_string($p);
    return $result;
}

public function executeQuery($q, $params = null){
    $this->makeConnection();        
    if ($params != null) {
        $queryParts = preg_split("/\?/", $q);
        if (count($queryParts) != count($params) + 1) {
            return false;
        }
        $finalQuery = $queryParts[0];
        for ($i = 0; $i < count($params); $i++) {
        $finalQuery = $finalQuery . $this->cleanParameters($params[$i]) . $queryParts[$i + 1];
        }
        $q = $finalQuery;
    }
    $results = $this->connection->query($q);

    return $results;

}
}?>

This in combination with a database factory keeps the data separated and clean.

<?php 
include_once 'database/Database.php';

class DatabaseFactory {
    private static $connection;

public static function getDatabase(){

   if (self::$connection == null) {
        $url = "URL";
        $user = "LOGIN";
        $passw = "PASSW";
        $db = "DB NAME";
        self::$connection = new Database($url, $user, $passw, $db);
    }
    return self::$connection;
}

} 
?>

After that you can easily make your (class based) your CRUD classes (objectname+DB)

<?php
include_once "//CLASS";
include_once "//DatabaseFactory";

class CLASSDB
{
private static function getConnection(){
    return DatabaseFactory::getDatabase();
}
public static function getById($Id){
    $results = self::getConnection()->executeQuery("SELECT * from DB WHERE Id = '?'", array(Id));

    if ($results){
        $row = $results->fetch_array();
        $obj = self::convertRowToObject($row);
        return $obj;
    } else {
        return false;
    }
}
public static function getAll(){
    $query = 'SELECT * from DB';
    $results = self::getConnection()->executeQuery($query);
    $resultsArray = array();
    for ($i = 0; $i < $results->num_rows; $i++){
        $row = $results->fetch_array();
        $obj = self::convertRowToObject($row);
        $resultsArray[$i] = $obj;
    }
    return $resultsArray;
}
public static function getName($Id){
    $results = self::getConnection()->executeQuery("SELECT column from DB WHERE Id = '?'", array($Id));

        $row = $results->fetch_array();
        return $row['column'];
}
public static function convertRowToObject($row){
    return new CLASSNAME(
        $row['prop'],
        $row['prop'],
        $row['prop'],
        $row['prop']
    );
}
public static function insert ($obj){
    self::getConnection()->executeQuery("INSERT INTO DB VALUES (null, '?', '?', '?')",
        array($obj->prop, $obj->prop, $obj->prop));
}
public static function update ($propToUpdate, $Id){
    self::getConnection()->executeQuery("UPDATE User SET COLTOUPDATE = ? WHERE Id = ?",
        array($propToUpdate, $Id));
}
}

And with this fine coding it's a piece of cake to select items in frontend:

include 'CLASSDB';

<php
$results = CLASSDB::getFunction();
        foreach ($results as $class) {  
?>
<li><?php echo $class->prop ?><li>
<php } ?>
-2

The easiest way to connect to MySQL server using php.

$conn=new mysqli("localhost", "Username", "Password", "DbName");
if($conn->connect_error)
{
    die("connection faild:".$conn->connect_error);
}
echo "Connection Successfully..!";
-3

localhost like this (MySQLi Procedural)

<?php

$servername ="localhost";

$username="username";//username like (root)

$password="password";//your database no password. (" ") 

$database="database";

$con=mysqli_connect($servername,$username,$password,$database);

if (!$con) {

    die("Connection failed: " . MySQL_connect_error());

}
else{

echo "Connected successfully";

}

Not the answer you're looking for? Browse other questions tagged or ask your own question.