PHP and MYSQLi - Binding parameters using loop and storage in an array?

It will be easier to explain with the following code (this is incorrect, by the way):

        $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();
        $genre = array();
            while ($stmt->fetch()) {
                $genre[] = $genres;
            }
        }

The above code gets the value from 'genreID' when 'dbGenre' is equal to '$ genre'. And then save the results in an array. But I do not work. What for? I think because "$ genre" is an array, so I need to loop around it to get a different value from "genreID" every time.

$ genre is an enumerated array containing movie genres, for example:

[0] => Action [1] => Adventure [2] => Fantasy

I need to compare the value (for example, "Action")

The 'genres' table contains two columns: genreID (INT) and dbGenre (VARCHAR)

genreID ( ).... .. dbGenre Action, genreID 1, $genre, genreID 1

?? , , , . !!

+5
3

SQL. SQL . , , .

, :

: loop over $genre array, SQL- .

if ($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), '?')) . ')';

if ($stmt->prepare($selectGenre_sql)) {
  $genre = array();
  . . .

bind_param() $genre:

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

  $stmt->execute();

  $stmt->bind_result($genres);

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

, PDO::mysql, . MySQLi .

+8

@

call_user_func_array args , , ! stmt- > bind_param

pdo ... u

ur:

if($stmt = ...same as yours) {
array_unshift($genre, str_repeat('i', count($genre)));
$temp = array();
foreach($genre as $key => $value) {
    $temp[$key] = &$genre[$key];
}
call_user_func_array(array($stmt, 'bind_param'), $temp);
etc...
}
+3

A few things.

  • Could this be because you are overwriting $ genre var, try changing it to $ genreArray in the case of sedond?
  • Make sure the database actually returns things (try in phpMyAdmin or something similar)

  • Try the following:

.

 $genreId = -1;
 $stmt->bind_results($genreId);
 $stmt->execute();
 while($stmt->fetch()){
  $genreArray[] = $genreId;
 }
0
source

All Articles