1

我有一个在应用程序中正常工作的旧 mysql 代码:

  $query = "
SELECT * FROM Tutor t  
WHERE 
(t.Tutorusername = '".mysql_real_escape_string($tutorusername)."')
AND
(t.Tutorpassword = '".mysql_real_escape_string($tutorpassword)."')
";


$num = mysql_num_rows($result = mysql_query($query));


while($row = mysql_fetch_array($result))
  {

  ...

}

但我现在想从 Mysql 更改为使用 mysqli。我的问题是下面的 mysqli 代码是否完全正确并且与上面的 mysql 代码相同?

$query = $mysqli->prepare("
    SELECT * FROM Tutor t  
    WHERE 
    (t.Tutorusername = '".mysqli_real_escape_string($tutorusername)."')
    AND
    (t.Tutorpassword = '".mysqli_real_escape_string($tutorpassword)."')
    ");

    $query->bind_result($Tutor);

    $num = $query->num_rows($result = $query->execute());


    while($row = $result->fetch())
      {

...

}
4

1 回答 1

2

此处无需使用preapre(),因为您正在连接 sql 字符串。

$sql="SELECT * FROM Tutor t
        WHERE 
        t.Tutorusername='".mysqli_real_escape_string($tutorusername)."'
        AND 
        t.Tutorpassword = '".mysqli_real_escape_string($tutorpassword)."'");

$result=$mysqli->query($sql);
if($result)
{
 $row=$result->fetch_row();
 if($row)
    print_r($row);
}

对于 prepare() 方法,您必须指定参数:

  $sql="SELECT * FROM Tutor t 
          WHERE t.Tutorusername=? AND t.Tutorpassword=?";

   $stmt=$mysqli->prepare($sql);
   $stmt->bind_param("s",$tutorusername);
   $stmt->bind_param("s",$tutorpassword);

   $stmt->execute(); 

   //I presume that the table "T" has three columns
   $stmt->bind_result($col1,$col2,$col2);
   while($stmt->fetch())
   {
     echo "<br/>", $col1,$col2,$col3;
    }

PS:阅读 mysqli API 的 PHP 手册。

于 2012-06-09T03:11:01.490 回答