Connection with mysqli() does not work, why?

2019-06-11 01:37发布

问题:

I have a strange problem when connecting to a mysql database in Microsoft Azure. When I use this command to connect to the databases the queries works successfully.

$con = mysql_connect($mysql_db_hostname, $mysql_db_user, $mysql_db_password) or die("Could not connect database");
mysql_select_db($mysql_db_database, $con) or die("Could not select database");

But when I use this command it won't work:

$con = new mysqli($mysql_db_hostname, $mysql_db_user, $mysql_db_password, $mysql_db_database);
if ($con->connect_error)
{
    die("Database selection failed: " . $con->connect_error);   
}

I do not get the message "Database selection failed: " . $con->connect_error. Any idea why the first code work and not the other one?

I'm using the connection for this php code:

<?php  require_once ("/connect.php");
if(isset($_POST['username']) && !empty($_POST['username'])){
     $username=mysql_real_escape_string($_POST['username']);
}else{
     $message[]='Please enter username';
}
if(isset($_POST['password']) && !empty($_POST['password'])){
     $password=mysql_real_escape_string($_POST['password']);
}else{
     $message[]='Please enter password';
}
$countError=count($message);
if($countError > 0){
 for($i=0;$i<$countError;$i++){
          echo ucwords($message[$i]).'<br/><br/>';
 }
}else{
   $query="select * from users where username='$username' and password='$password'";
   $res=mysql_query($query);
   $checkUser=mysql_num_rows($res);
   if($checkUser > 0){
      echo 'correct';
   }else{
       echo ucwords('please enter correct user details');
   }
}

回答1:

You cannot mix & match between mysql_* functions and mysqli_* functions. Either you use ALL mysql_* (deprecated) or you use ALL mysqli_* functions. You changed the connection, apparently, but did not yet change, for instance, mysqli_query to mysqli_query and etc.

Do note that there is not necessarily a 1-to-1 correspondence between the 2 APIs. In other words, you can't just add an "i" and hope it will always work - there are some conceptual and syntactic and etc changes that you will need to take into account.

In any event, look at every occurrence of "mysql_" in your PHP code and convert it to use "mysqli_*" functions and that should solve your problem.