PHP PDO MYSQL - 获取返回无结果的地方

时间:2015-03-03 19:24:48

标签: php mysql pdo

我正在尝试获取列等于该列中的值的结果,我的代码在从查询中删除了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);
}

3 个答案:

答案 0 :(得分:3)

你的参数数组是错误的,它应该是:

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

注意那里的:。同样,您的值实际上是数组。当PDO开始绑定时,它会期待字符串,并找到一个数组,所以很可能是你的查询(如果参数首先起作用的话),应该产生相当于:

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

答案 1 :(得分:2)

您正在绑定数组。

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

['theme']相当于array(0 => 'theme')

答案 2 :(得分:0)

你可以留在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的值。