I have this code
$query = mysql_query("SELECT * FROM users ORDER BY exp DESC LIMIT ".$lim.", 10");
and
while($row = mysql_fetch_array($query))
but what's the mysqli equivalent to this (featuring prepared statements). I can't get along.
I have this code
$query = mysql_query("SELECT * FROM users ORDER BY exp DESC LIMIT ".$lim.", 10");
and
while($row = mysql_fetch_array($query))
but what's the mysqli equivalent to this (featuring prepared statements). I can't get along.
Not tested, but it should be like this. And what is $lim variable? Is it custom way to show what LIMIT is ?
$query = $mysqli->query("SELECT * FROM users ORDER BY exp DESC LIMIT ".$lim.", 10");
if ($stmt = $mysqli->prepare($query)) {
$stmt->execute();
//NOTE: depends on your SQL statement, you bind your columns here, and store into var. I don't know how many columns you need to bind with your select statement, but idea is like this.
$stmt->bind_result($var1, $var2, var3, *(and so on)*);
while ($stmt->fetch()) {
printf ("%s (%s)\n", $name, $code);
}
$stmt->close();
}
Prepared statement placeholders can only be used in places where the SQL allows an expression, but LIMIT
requires its parameter to be a literal. Since you can't use a placeholder there, the mysqli
equivalent is basically the same as the mysql
version, there's no benefit from using a prepared statement. The only difference is that mysqli_query
requires the connection object as its first argument.
$query = mysqli_query($conn, "SELECT * FROM users ORDER BY exp DESC LIMIT ".$lim.", 10");
while($row = mysqli_fetch_array($query)) {
...
}
Here is an example:
$limit = 10;
$user = "john";
$sql="SELECT * FROM users WHERE first_name = ? ORDER BY exp DESC LIMIT ?";
$stmt = $db->stmt_init(); // Initiate prepared statement
if(!$stmt->prepare($sql)){// prepare query, but if it fails get store the error in $error. echo error if you are debugging
$error = $stmt->error;
}else{
$stmt->bind_param("si", $user, $limit);//bind values -- Must be variable --list them by order. First parameter is the data type, and the rest are values to bind
// Data types include "i" - for integer, "d" - for decimal integer, "s" - for string and "b" - for BLOB
$stmt->execute();//execute the prepared statement
$result = $stmt->get_result(); //store mysql object so that you can use it later to fetch_array or num_row
}
//Using the $result mysqli object we stored
$numrows=$result->num_rows;// Get total number of rows
if(!numrows){
echo "No results found";
}else{
while($row = $result->fetch_assoc()){
echo $row['first_name'];
}
}