0

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?

user1214840
  • 189
  • 1
  • 6
  • 14

2 Answers2

16

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

Dharman
  • 30,962
  • 25
  • 85
  • 135
Kermit
  • 33,827
  • 13
  • 85
  • 121
0

This warning will be logged anytime you try to execute a query without a valid connection object being available.

In your case you thought you had a valid connection object available, but you created it using mysqli while your query is being executed using mysql. Those are two different APIs and so the mysql_query function was looking for a mysql connection object and didn't find it.

Vincent
  • 1,741
  • 23
  • 35