如何在 mysqli 的参数化查询中传递任何值?

How to pass any value in parameterised query in mysqli?

Objective: 在 mysqli 参数化查询

的 where 短语中传递任何值

代码:

<?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);
?>

观察: 在 mysql 提示符中,

mysql> SELECT name, age from student WHERE name LIKE  "%%" AND age LIKE "%%";

显示所有记录。

但是,上面的php代码没有显示任何记录。

请帮助我在参数化查询中传递任何值。

在 "any" 值下,您假设任何 string 值。因此,您必须为 $age 变量使用正确的类型:s,而不是 i

<?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]";
}