Php – Access denied for user ”@’localhost’ (using password: NO)

MySQLPHP

Attempting to connect to localhost sql db using the following code (Not doing anything with query at this point just want the query to execute):

<?php

$host     = "localhost";
$port     = 3306;
$socket   = "";
$user     = "root";
$password = "Password1";
$dbname   = "CIIP_WIKI";

$con = new mysqli($host, $user, $password, $dbname, $port);

if(!$con)
{
echo ("db connection failed!");
die ('Could not connect to the database server' . mysqli_connect_error());
}

else {
    echo ("db connection established.");
    echo ("<br/>");
    }

$query = sprintf("SELECT first_name FROM actor WHERE actor_id='1'");

$result = mysql_query($query);

$con->close();

?>

I keep getting the following…

Welcome

db connection established.

Warning: mysql_query(): Access denied for user ''@'localhost' (using password: NO) in C:\Program Files (x86)\EasyPHP-12.1\www\Cisco Wiki\index.php on line 31

Warning: mysql_query(): A link to the server could not be established in C:\Program Files (x86)\EasyPHP-12.1\www\Cisco Wiki\index.php on line 31

Why does this not work?

Best Answer

This is because you create a connection using mysqli_ and then use mysql_ to try to fetch your result. They are different API's.

<?php

/* You should enable error reporting for mysqli before attempting to make a connection */
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$mysqli = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');

/* Set the desired charset after establishing a connection */
mysqli_set_charset($mysqli, 'utf8mb4');

printf("Success... %s\n", mysqli_get_host_info($mysqli));

Example taken from the PHP manual