【问题标题】:php PDO fetchAll with foreach not working带有foreach的php PDO fetchAll不起作用
【发布时间】:2017-06-16 07:09:19
【问题描述】:

我在从数据库中选择 PDO 以根据文章(主要是页面)生成动态站点地图文件时遇到一些问题。 PHP 没有抛出任何错误,因为我在错误日志中没有看到任何错误。这是代码。

选择语句片段

$q = $db->prepare("SELECT * FROM articles ORDER BY aid ASC");
$r = $q->fetchAll(PDO::FETCH_ASSOC);

每个片段 + XML

foreach($r as $row) {

$format_date = date('Y-m-d', $row['date']);
$format_slug = strtolower($row['slug']);

echo '
<url>
    <loc>'.$format_slug.'</loc>
    <lastmod>'.$format_date.'</lastmod>
    <changefreq>monthly</changefreq>
</url>
';

}

“FOREACH”之前的 XML 数据

echo '<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
      <loc></loc>
      <lastmod>2017-01-27</lastmod>
      <changefreq>weekly</changefreq>
      <priority>1.0</priority>
</url>
<url>
      <loc>contact-us</loc>
      <lastmod>2017-01-27</lastmod>
      <changefreq>yearly</changefreq>
</url>
';

“FOREACH”之后的 XML 数据

echo '</urlset>';

我在页面最顶部为 XML 输出使用了正确的 PHP 标头

header('Content-Type: text/xml');

所以我导航到站点地图 url,回显语句中的预定义数据被返回,在这种情况下,BEFORE "FOREACH" 部分中的 2 个数据 sn-ps,当然还有 在“FOREACH”之后返回。

但是由于某些奇怪的原因,没有从数据库中获取数据,即使脚本似乎可以正常工作。我错过了什么吗?

【问题讨论】:

    标签: php mysql xml pdo foreach


    【解决方案1】:

    您是否忘记在statement 上致电Execute

    【讨论】:

      【解决方案2】:

      您需要执行该语句。

      $q = $db->prepare("SELECT * FROM articles ORDER BY aid ASC");
      $q->execute();
      $r = $q->fetchAll(PDO::FETCH_ASSOC);
      

      您也可以使用 PDO::query http://php.net/manual/en/pdo.query.php

      【讨论】:

      • 谢谢你,有点奇怪,我忘记了,我猜我睡眠不足,哈哈。
      猜你喜欢
      • 2015-03-31
      • 1970-01-01
      • 1970-01-01
      • 2013-02-05
      • 1970-01-01
      • 2016-04-16
      • 1970-01-01
      • 1970-01-01
      • 2013-03-01
      相关资源
      最近更新 更多