使用MySQLi动态绑定准备语句中的参数

时间:2014-02-20 02:36:57

标签: php mysqli prepared-statement

就像标题所说的那样,我在这里搜索并尝试了几乎所有内容,但没有成功。

我尝试在更深入之前测试一些非常简单的东西,以确保它有效。但即使是最简单的,我总是得到0结果,我知道有67个结果。

我的代码出了什么问题?

由于

$conn = connect(); // connect to the db

$a_bind_params = array('love', 'circle');
$a_param_type = array('s', 's');

$totalKeywords = count($a_bind_params);

$q = 'SELECT id, name
    FROM album
    WHERE name LIKE ?';

for ($i = 1; $i < $totalKeywords; $i++) {
    $q .= ' AND name LIKE ?';
}

echo $q; // for testing purposes: verify that query is OK

// bind parameters.
$param_type = '';
$n = count($a_param_type);

for($i = 0; $i < $n; $i++) {
    $param_type .= $a_param_type[$i];
}

/* with call_user_func_array, array params must be passed by reference */
$a_params = array();
$a_params[] = & $param_type;

for($i = 0; $i < $n; $i++) {
  /* with call_user_func_array, array params must be passed by reference */
  $a_params[] = & $a_bind_params[$i];
}

$stmt = $conn->prepare($q);

/* use call_user_func_array, as $stmt->bind_param('s', $param); does not accept params array */
call_user_func_array(array($stmt, 'bind_param'), $a_params);


$stmt->execute();
$stmt->store_result();
$num_rows = $stmt->num_rows;

echo $num_rows; // how many found ?

$stmt->bind_result($id, $name);

while($stmt->fetch()) {
    echo $name;
}

$stmt->free_result();
$stmt->close();
$conn->close(); 

1 个答案:

答案 0 :(得分:1)

查询

没有67行
SELECT id, name
FROM album
WHERE name LIKE 'love' AND name LIKE 'circle'

OR条款中应该AND而不是WHERE

您可能还需要%love%%circle%