Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQLi Equivalent Of MySQL Code

Tags:

php

mysql

mysqli

Can you give me the 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>";
}
like image 878
Tom Granot Avatar asked Feb 02 '11 12:02

Tom Granot


2 Answers

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).

like image 116
ircmaxell Avatar answered Sep 22 '22 14:09

ircmaxell


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>";
}
like image 29
FX LEGER Avatar answered Sep 24 '22 14:09

FX LEGER