MySQLi等效的MySQL代码

时间:2011-02-02 12:54:07

标签: php mysql mysqli

你能给我相当于MySQLi的这段代码吗?无法做对。

<?php
if(mysql_num_rows(mysql_query("SELECT userid FROM users WHERE userid = '$userid'"))){
//code to be exectued if user exists
} 
?>

编辑:小心向我解释有什么问题?

$mysqli = new mysqli($host, $username, $pass, $db);

if ($mysqli->connect_error) {
    die('The Server Is Busy. Please Try Again Later.');
}
$result = $mysqli->query("SELECT userid FROM users WHERE userid = '$userid'");
if ($result->num_rows) {
    echo "<h1>AWESOME</h1>";
}

3 个答案:

答案 0 :(得分:15)

嗯,从OO意义上说,它将来自:

if(mysql_num_rows(mysql_query("SELECT userid FROM users WHERE userid = '$userid'"))){
    //code to be exectued if user exists
}

To(假设为数字用户ID):

$result = $mysqli->query("SELECT userid FROM users WHERE userid = ".(int) $userid);
if ($result->num_rows) {
    //code
}

To(假设字符串userid):

$result = $mysqli->query("SELECT userid FROM users WHERE userid = '". $db->real_escape_string($userid) . "');
if ($result->num_rows) {
    //code
}

To(假设准备好的陈述):

$stmt = $mysqli->prepare("SELECT userid FROM users WHERE userid = ?");
$stmt->bind_param('s', $userid);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows) {
    //code
}

现在,假设你正在使用MySQLi的OOP版本(你应该是,恕我直言,因为它在很多方面让生活更轻松)。

答案 1 :(得分:1)

我会这样做:

$result = $mysqli->query("SELECT userid FROM users WHERE userid = '$userid'");
$row = mysqli_fetch_assoc($result);

if ($row['userid'] > 0 ) {
  echo "<h1>AWESOME</h1>";
}

答案 2 :(得分:0)

$connection = mysqli_connect(...);

if(mysqli_num_rows(mysqli_query($connection,"SELECT userid FROM users WHERE userid = '$userid'"))){
//code to be exectued if user exists
} 

我会这样做:

$connection = mysqli_connect(...);

$result = mysqli_query(
  $connection,
  "SELECT COUNT(*) AS cnt FROM users WHERE userid = '$userid'"
) or die(mysqli_error());  //use proper error handling here: or die() used for brevity

$row = mysqli_fetch_assoc($result);

if($row['cnt'] > 0) {
  //do your thing
}