MySQLi Equivalent Of MySQL Code
Can you give me th开发者_如何学Ce equivalent of this code im MySQLi? Can't get it right.
<?php
if(mysql_num_rows(mysql_query("SELECT userid FROM users WHERE userid = '$userid'"))){
//code to be exectued if user exists
}
?>
EDIT: Care to explain to me what is wrong?
$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>";
}
Well, in an OO sense, it would go from:
if(mysql_num_rows(mysql_query("SELECT userid FROM users WHERE userid = '$userid'"))){
//code to be exectued if user exists
}
To (assuming numeric userid):
$result = $mysqli->query("SELECT userid FROM users WHERE userid = ".(int) $userid);
if ($result->num_rows) {
//code
}
To (assuming string userid) :
$result = $mysqli->query("SELECT userid FROM users WHERE userid = '". $db->real_escape_string($userid) . "');
if ($result->num_rows) {
//code
}
To (assuming prepared statements) :
$stmt = $mysqli->prepare("SELECT userid FROM users WHERE userid = ?");
$stmt->bind_param('s', $userid);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows) {
//code
}
Now, that's assuming you're using the OOP version of MySQLi (which you should be, IMHO, since it makes life easier in a lot of ways).
I would do it this way:
$result = $mysqli->query("SELECT userid FROM users WHERE userid = '$userid'");
$row = mysqli_fetch_assoc($result);
if ($row['userid'] > 0 ) {
echo "<h1>AWESOME</h1>";
}
$connection = mysqli_connect(...);
if(mysqli_num_rows(mysqli_query($connection,"SELECT userid FROM users WHERE userid = '$userid'"))){
//code to be exectued if user exists
}
Way I'd do it:
$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
}
精彩评论