【发布时间】:2018-12-03 06:20:04
【问题描述】:
我正在尝试为用户输入编写准备好的语句。参数编号是可变的,取决于用户输入。我正在尝试这段代码
php代码:
$string = "my name";
$search_exploded = explode( " ", $string );
$num = count( $search_exploded );
$cart = array();
for ( $i = 1; $i <= $num; $i ++ ) {
$cart[] = 's';
}
$str = implode( '', $cart );
$inputArray[] = &$str;
$j = count( $search_exploded );
for ( $i = 0; $i < $j; $i ++ ) {
$inputArray[] = &$search_exploded[ $i ];
}
print_r( $inputArray );
foreach ( $search_exploded as $search_each ) {
$x ++;
if ( $x == 1 ) {
$construct .= "name LIKE %?%";
} else {
$construct .= " or name LIKE %?%";
}
}
$query = "SELECT * FROM info WHERE $construct";
$stmt = mysqli_prepare( $conn, $query );
call_user_func_array( array( $stmt, 'bind_param' ), $inputArray );
if ( mysqli_stmt_execute( $stmt ) ) {
$result = mysqli_stmt_get_result( $stmt );
if ( mysqli_num_rows( $result ) > 0 ) {
echo $foundnum = mysqli_num_rows( $result );
while( $row = mysqli_fetch_array( $result, MYSQLI_ASSOC ) ) {
echo $id = $row['id'];
echo $name = $row['name'];
}
}
}
当我 print_r $inputArray 的输出是这样的:
Array ( [0] => ss [1] => my [2] => name )
错误日志中没有显示错误。 我在这里做错了什么请告诉我。
【问题讨论】:
-
你在 $query 中得到了什么?
-
你在 " " 上爆炸你的
$string,所以你会期望你的foreach()给你两个条目:my和name。 -
这是查询:SELECT * FROM info WHERE name LIKE %?% or name LIKE %?%
-
是的,我想在姓名栏中搜索“我的”和“姓名”。
-
将 LIKE 与绑定变量一起使用时,您必须在绑定变量中包含 % 符号,而不是 SQL。
标签: php mysqli prepared-statement