0

I don't know why my code doesn't return true, the while loop works fine, but there's a problem.

$PDO_result = $db_PDO->prepare("SELECT * FROM nnm_anime INNER JOIN nnm_anime_info ON nnm_anime.a_id = nnm_anime_info.a_id WHERE a_name LIKE '?%' ");
$PDO_result->bindParam(1, $pismenka[$i]);
$PDO_result->execute();

Here when I var_dump() $PDO_result I get one item in array so the following while loop should work:

while($row = $PDO_result->fetch(PDO::FETCH_ASSOC))

but it doesn't.

Working MySQLi:

$result = mysqli_query($connect_to_db, "SELECT * FROM nnm_anime INNER JOIN nnm_anime_info ON nnm_anime.a_id = nnm_anime_info.a_id WHERE a_name LIKE '$pismenka[$i]%' ");

while($row = mysqli_fetch_array($result))
Ivan
  • 34,531
  • 8
  • 55
  • 100
Patrik Horváth
  • 177
  • 1
  • 1
  • 15

1 Answers1

2

The most simple solution would be to change $pdo->fetch(PDO::FETCH_ASSOC) to $pdo->fetchAll(PDO::FETCH_ASSOC)

fetchAll returns ALL rows in the requested query, while fetch only gets 1 row (the first)

Example:

<?php


try {

    $PDO_result = $db_PDO->prepare("SELECT * FROM nnm_anime INNER JOIN nnm_anime_info ON nnm_anime.a_id = nnm_anime_info.a_id WHERE a_name LIKE ?");

    //Execute by inserting an array:
    if (!$PDO_result->execute([$pismenka[$i] . "%" ])) { //Added ."%" 
        die('Error!');
    }

    //Fetch rows:
    $rows = $PDO_result->fetchAll(PDO::FETCH_ASSOC);

    //Go trough each row:
    foreach ($rows as $row) {
        //Do something
    }

    //Catch exceptions thrown by PDO
} catch (PDOException $ex) {
    print_r($ex);
}
MrK
  • 1,060
  • 9
  • 23
  • fetch should return 1st row then 2nd then 3rd ..... as is described in PHP.net or not ? – Patrik Horváth Sep 03 '17 at 16:40
  • I am not 100% sure about that, but take a look at this answer, it kind of reminds me of your question: https://stackoverflow.com/questions/19488364/how-to-properly-use-while-loop-in-pdo-fetchall But with `fetchAll` you do not have to use while at all, you simply get it all in one associative array but IMO it does the same job, and `fetchAll`is clearer in the context of what you are actually doing – MrK Sep 03 '17 at 16:42
  • try putting your code inside `try{ code here } catch(PDOException $ex){ print_r($ex); }` – MrK Sep 03 '17 at 16:48
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/153559/discussion-between-kristian-hareland-and-patrik-horvath). – MrK Sep 03 '17 at 16:55
  • 1
    Should be `execute([ $pismenka[$i] . "%" ])` since the `%` was in the original query. – tadman Sep 03 '17 at 17:32
  • 1
    @tadman that is correct, i forgot to update the answer after me and OP had a skype session to figure out the issue. Will update :) – MrK Sep 04 '17 at 18:16