Objective: to pass any value in where phrase of mysqli parameterised query
code:
<?php
$name="%%";
$age="%%";
$name_op=null;
$age_op=null;
require_once("dbc.php");
$query="SELECT name, age from student WHERE name LIKE ? AND age LIKE ?";
$stmt=mysqli_prepare($dbc, $query);
mysqli_bind_param($stmt, "si", $name, $age);
mysqli_stmt_execute($stmt);
mysqli_bind_result($stmt, $name_op, $age_op);
while(mysqli_bind_fetch($stmt)){
echo "name : $name_op age: $age_op";
}
mysqli_stmt_close($stmt);
mysqli_close($dbc);
?>
Observation: In mysql prompt,
mysql> SELECT name, age from student WHERE name LIKE "%%" AND age LIKE "%%";
shows all the records.
But, the above php code doesn't display any record.
Please help me in passing any value in parameterised query.
Under "any" value you are assuming any string value. Hence, you must use the correct type: s
, not i
for the $age variable.
<?php
require_once("dbc.php");
$name="%%";
$age="%%";
$query = "SELECT name, age from student WHERE name LIKE ? AND age LIKE ?";
$stmt = $dbc->prepare($query);
$stmt->bind_param("ss", $name, $age);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()){
echo "name : $row[name] age: $row[age]";
}