简体   繁体   中英

Running PHP5: access denied to MySQLi connection but success for MySQL

I ran this code to get the output shown in image below:

<?php
  phpinfo();
?>

在此输入图像描述

Trouble is, I cannot figure out why this works:

$conn = @mysql_connect('host', 'user', 'pass') or die(mysql_error());
      @mysql_select_db('dbName') or die(mysql_error());

      $query="SELECT * FROM Clients";

     $result = @mysql_query($query) or die(mysql_error());
      if ($result)
      {
            $outp = "";
      while ($row = mysql_fetch_assoc($result))
      {

        if ($outp != "") {$outp .= ",";}
        $outp .= '{"ClientID":"'  . $row["cID"] . '",';
        $outp .= '"ClientsName":"'   . $row["clientsName"] . '"}'; 
      }
      mysql_free_result($result);
      }
    $outp ='{"records":['.$outp.']}';
    echo($outp);

But this does not:

$conn = new mysqli("host", "user", "pass", "dbName");
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
echo "Connected successfully";
$result = $conn->query("SELECT * FROM Clients");

$outp = "";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
    if ($outp != "") {$outp .= ",";}
    $outp .= '{"ClientID":"'  . $rs["cID"] . '",';
    $outp .= '"ClientsName":"'   . $rs["clientsName"] . '"}'; 
}
$outp ='{"records":['.$outp.']}';
$conn->close();

echo($outp);

The error that I get is:

Connection failed: Access denied for user 'user'@'host' to database 'dbName'

I read that as long as PHP5 is running, MySQLi is also already installed. What else might I need to check for? Maybe I am doing something wrong in my code? This is my first attempt at MySQLi, I haven't connected to a database in years, had to rummage through old code just to get the old SQL way to connect to database.

Your code looks perfectly fine.

Make sure there are no typos in the auth details.

Secondly, MySQL users are binded to hosts. For example root@localhost . If you're connecting from a remote host, make sure you have set up a user like root@123.123.123.123 or allow all hosts by using the % wildcard like root@% .

Hope this helps.

A while back I bumped into a sql client challenge where the version of php caused the client to refuse to connect to the server in mysqli for an arcane security reason. To resolve the issue, I had to turn on logging for mysql (debug logging) and check the debug log on the server after an attempt. Your problem sounds very familiar and may even be the same one. It required altering the password type if I recall correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM