5
$genre = array(
    'Action',
    'Adventure',
    'Fantasy'
);
$selectGenre_sql = 'SELECT genreID FROM genres WHERE dbGenre = ?';

if ($stmt->prepare($selectGenre_sql)) {
    // bind the query parameters
    $stmt->bind_param('s', $genre);
    // bind the results to variables
    $stmt->bind_result($genres);
    // execute the query
    $stmt->execute();
    $array1 = array();
    while ($stmt->fetch()) {
        $array1[] = $genres;
    }
}

上面的代码从genreIDwhen dbGenreis equal to获取值$genre。然后将结果存储在一个数组中。但它不起作用,因为它$genre是一个数组,所以我需要遍历它以从genreID每次获取不同的值。

'genres' 表包含两列:genreID (INT)dbGenre (VARCHAR)

我只需要每个genreID(即一个数字)...假设当dbGenre 等于Action 时,将genreID 存储在array1 中,然后循环$genre 数组以获取下一个值的genreID 并再次存储在数组 1 中。

我该如何解决?

4

2 回答 2

8

您不能将数组绑定到 SQL 参数。您可以在 SQL 中使用参数来代替单个文字值。不是值列表、表达式、列名或表名。

要解决您的情况下的任务,您可以使用以下两种解决方案之一:

第一个解决方案:遍历$genre数组,一次绑定每个值,并为每个值执行 SQL 查询。

$stmt->prepare($selectGenre_sql);
$genre = array();
foreach ($gengre as $genreID) {
    $stmt->bind_param('s', $genreID);
    $stmt->execute();
    $stmt->bind_result($genres);
    while ($stmt->fetch()) {
        $genre[] = $genres;
    }
}

第二种解决方案:执行一次查询,带有多个参数,数组中的每个值一个。这需要一些棘手的代码来在 SQL 查询中构建可变数量的?占位符,用逗号分隔。

$selectGenre_sql = 'SELECT genreID FROM genres WHERE dbGenre IN ('
 . join(',', array_fill(0, count($genre), '?')) . ')';

您还需要根据数组bind_param()中的元素使用可变数量的参数进行棘手的调用:$genre

$stmt->prepare($selectGenre_sql);
$temp = array();
foreach ($genre as $key => $value) {
    $temp[] = &$genre[$key];
}

array_unshift($genre, str_repeat('i', count($genre)));
call_user_func_array(array($stmt, 'bind_param'), $genre);

$stmt->execute();

$stmt->bind_result($genres);

$array1 = array();
while ($stmt->fetch()) {
    $array1[] = $genres;
}

您可能要考虑使用PDO_MYSQL,因为从数组中绑定参数更容易。MySQLi 界面在这种情况下非常尴尬。

于 2009-03-09T20:47:54.657 回答
-1

一些东西。

  • 可能不是因为您覆盖了 $genre var,尝试在 sedond 情况下将其更改为 $genreArray 吗?
  • 确保数据库实际上正在返回东西(在 phpMyAdmin 或类似的东西中尝试)

  • 尝试像这样处理:

.

 $genreId = -1;
 $stmt->bind_results($genreId);
 $stmt->execute();
 while($stmt->fetch()){
  $genreArray[] = $genreId;
 }
于 2009-03-09T20:03:47.870 回答