PHP PDO MYSQL - 在没有返回结果的情况下获取

PHP PDO MYSQL - Fetch where returning no results

我正在尝试获取列等于该列中的值的结果,我的代码 运行s 从查询中删除了 where 子句,但没有抛出任何错误,但 foreach没有 运行.

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

这就是我的功能 为什么 我有绑定;

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

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

你可以留在 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;
}

您仍然需要为 $myTheme$myId 提供一个值。

您正在绑定数组。

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

['theme'] 等同于 array(0 => 'theme')

你的参数数组有误,应该是:

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

请注意其中的 :。同样,您的值实际上是数组。当 PDO 开始绑定时,它将期待字符串,并找到一个数组,因此很可能您的查询(如果参数首先起作用)将产生等效于:

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