How to bind mysqli parameters using loop and store results in array?

后端 未结 2 895
無奈伤痛
無奈伤痛 2020-12-21 00:37
$genre = array(
    \'Action\',
    \'Adventure\',
    \'Fantasy\'
);
$selectGenre_sql = \'SELECT genreID FROM genres WHERE dbGenre = ?\';

if ($stmt->prepare($se         


        
相关标签:
2条回答
  • 2020-12-21 00:47

    You can't bind an array to an SQL parameter. You can use a parameter in SQL in place of a single literal value. Not a list of values, or an expression, or a column name or table name.

    To solve the task in your case, you can use either of two solutions:

    First solution: loop over $genre array, bind each value one at a time and execute the SQL query for each value.

    $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;
        }
    }
    

    Second solution: execute the query once, with multiple parameters, one for each value in the array. This requires some tricky code to build a variable number of ? placeholders in the SQL query, separated by commas.

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

    Also you need to get tricky calling bind_param() with a variable number of arguments based on the elements in your $genre array:

    $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;
    }
    

    You might want to consider using PDO_MYSQL because it's easier to bind parameters from an array. The MySQLi interface is pretty awkward for this case.

    0 讨论(0)
  • 2020-12-21 01:01

    A few things.

    • Could it be is't because your overwriting the $genre var, try changeing it to $genreArray in the sedond case?
    • Make sure that the database is actually returning things (try it in phpMyAdmin or something similar)

    • Try processing like this:

    .

     $genreId = -1;
     $stmt->bind_results($genreId);
     $stmt->execute();
     while($stmt->fetch()){
      $genreArray[] = $genreId;
     }
    
    0 讨论(0)
提交回复
热议问题