简体   繁体   English

php PDO fetchAll 与 foreach 不工作

[英]php PDO fetchAll with foreach not working

I'm having some problems with PDO selecting from Database in order to generate dynamic Sitemap file based on articles (essentially pages).我在从数据库中选择 PDO 以生成基于文章(基本上是页面)的动态站点地图文件时遇到了一些问题。 PHP is not throwing any errors as I don't see any errors in the error log. PHP 没有抛出任何错误,因为我在错误日志中没有看到任何错误。 Here is the code.这是代码。

SELECT STATEMENT SNIPPET选择语句片段

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

FOR EACH SNIPPET + XML对于每个片段 + 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>
';

}

XML DATA BEFORE "FOREACH" “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>
';

XML DATA AFTER "FOREACH" “FOREACH”之后的 XML 数据

echo '</urlset>';

And I am using proper PHP header for the XML output at the very top of the page which is我在页面最顶部的 XML 输出中使用了正确的 PHP 标头

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

So ones I navigate to the Sitemap url, the predefined data in the echo statements is returned, in this case the 2 data snippets in the BEFORE "FOREACH" part and of course the AFTER "FOREACH" is returned.因此,我导航到站点地图 url,返回 echo 语句中的预定义数据,在这种情况下,返回BEFORE "FOREACH"部分中的 2 个数据片段,当然返回AFTER "FOREACH"

However for some odd reason no data is being fetched from the database even truth the script seems to work.然而,由于某种奇怪的原因,即使脚本似乎工作,也没有从数据库中获取数据。 Am I missing something?我错过了什么吗?

You need to execute the statement.您需要执行该语句。

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

Alternatively you can use PDO::query http://php.net/manual/en/pdo.query.php .或者,您可以使用 PDO::query http://php.net/manual/en/pdo.query.php

你忘记在statement上调用Execute了吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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