mysql代码vs mysqli代码

时间:2014-02-04 18:03:34

标签: mysql sql mysqli

我已经尝试将一段代码从mysql转换为mysqli,下面的代码是mysql代码,这样可以正常工作并让用户正确登录。

<?php
 if($_POST){
 $username=mysql_real_escape_string($_POST['username']); //Protects against SQL Injection
 $password=mysql_real_escape_string($_POST['password']); // Protects against SQL Injection

 $sql = mysql_query("SELECT * FROM usertable WHERE userID ='".$username."' AND userPass ='".md5($password)."'") or die(mysql_error());
 $res=mysql_num_rows($sql);

 if($res>0){
 $rs_login=mysql_fetch_assoc($sql);
 $uid=$rs_login['userID'];
 $_SESSION['sess_uid']=$uid;
 header("Location: index.php");
 die();

 } 

 else{
 echo '<div class="error">Incorrect Username or Password</div>';
 echo '<br/>';
 }
 }

 ?>

下面的代码不起作用,我收到错误“警告:mysqli_num_rows()正好需要1个参数,2给出”。我知道查询存在问题,但我无法搞清楚。

<?php
  $mysqli = mysqli_connect("localhost", "root", "password", "dbname") or die ('Could not connect to database!');

  if(isset( $_POST['username']) && isset($_POST['password'])){

  $username = mysqli_real_escape_string($mysqli, $_POST['username']);
  $password = mysqli_real_escape_string($mysqli, md5($_POST['password']));

  $sqllogin = "SELECT * FROM usertable WHERE userID = '".$username."'  AND userPass = '".$password."' LIMIT 1" ;

  $result = mysqli_query($mysqli,$sqllogin);
  $count = mysqli_num_rows($mysqli,$result);   

  if (!$resuult) {
     die(mysqli_error($mysqli));
        }           
     if ($count > 0) {
 $data = mysqli_fetch_assoc($count);
 return $data;
 $uid=$rs_login['userID'];
 $_SESSION['sess_uid']=$uid;
 header('Location: index.php');

} else {
  echo '<div class="error">Incorrect Username or Password</div>';
  echo '<br/>';
 }

}
?>    

1 个答案:

答案 0 :(得分:2)

  

下面的代码不起作用,我收到错误“警告:mysqli_num_rows()正好需要1个参数,2给出”。我知道查询存在问题,但我无法搞清楚。

不,查询没有问题,请阅读错误说明:

  

“警告:mysqli_num_rows()正好需要1个参数,2给出”

Google搜索mysqli_num_rows&gt;&gt; Documentation

需要一个参数;一个mysqli_result

因此,请使用该参数调用它,或使用文档中的一个示例:

mysqli_num_rows($result);