简体   繁体   中英

PHP PDO MYSQL - Fetch where returning no results

I'm trying to fetch results where a column is equal to a value in that column, my code runs with the where clause removed from the query but with it no errors are thrown but the foreach doesn't run.

$themes = Singlequery ('SELECT * FROM items WHERE type = :theme ORDER BY id = :id DESC LIMIT 5', 
                      array('theme' => ['theme'], 'id' => ['id']), $conn);

<?php foreach ($themes as $theme) : ?>
      <li><a href="#"><?= $theme['name']; ?></a></li>
<?php endforeach; ?>

This is my function thats why I have bindings;

function Singlequery($query, $bindings, $conn)
{
    $stmt = $conn->prepare($query);
    $stmt->execute($bindings);

    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

Your parameters array is wrong, it should be:

array(':theme' => $theme, ':id' => $id)

Note the : in there. As well, your values are actually arrays. When PDO starts binding, it's going to be expecting strings, and finds an array, so most likely your query (if the parameters had worked in the first place),w ould be producing the equivalent of:

SELECT ... WHERE type = 'Array' ORDER BY id = 'id'

You're binding an array.

array('theme' => ['theme'], 'id' => ['id'])

['theme'] is equivalent to array(0 => 'theme')

You could stay in PHP:

$themes = Singlequery ('SELECT * 
                        FROM items 
                        WHERE type = :theme 
                        ORDER BY id = :id DESC 
                        LIMIT 5', 
                        array('theme' => $myTheme, 
                              'id'    => $myId), 
                        $conn);

foreach ($themes as $theme) {
  echo '<li><a href="#">'.$theme['name'].'</a></li>'.PHP_EOL;
}

You will still have to provide a value for $myTheme and $myId .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM