您可以将占位符的值放入数组变量中。在mysqli\u stmt\u bind\u param()中,可以使用splat运算符
...
-与下面的代码类似,因此您可以为单个表字段处理不同数量的占位符及其值。
您可以这样做:
$interest_array = array('basketball', 'basketball', 'basketball', 'basketball');
$s_marks = str_repeat("s", count($interest_array));
mysqli_stmt_bind_param($stmt, $s_marks, ...$interest_array);
这是:
mysqli_stmt_bind_param($stmt, $s_marks, ...$interest_array);
将被视为:
mysqli_stmt_bind_param($stmt, "ssss", $interest1,$interest2,$interest13, $interest4);
您的更新代码(尚未测试):
$Interest = $_GET['interestId'];
$sql = "SELECT * from User WHERE (Interest1 = ? OR Interest2 = ? OR Interest3 = ?) OR ? = 'Any Interest';";
$placeholder_count = substr_count($sql, '?');
$s_marks = str_repeat("s", $placeholder_count); // creates sss string
$interest_array = array_fill(0, $placeholder_count, $Interest); // creates an array of the same values.
echo "<h1 class='contact-intro'>";
echo " Welcome to the business card library for $Interest! </h1>";
$stmt = mysqli_stmt_init($link);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL statement failed";
} else {
mysqli_stmt_bind_param($stmt, $s_marks, ...$interest_array);
mysqli_stmt_execute($stmt);
}
其余代码将仅根据sql字符串中占位符的数量来采用。