Patrik Horváth
Patrik Horváth

Reputation: 177

PHP MySQLi to PDO?

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))

Upvotes: 0

Views: 643

Answers (1)

MrK
MrK

Reputation: 1078

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

Upvotes: 2

Related Questions