【问题标题】:foreach loop not enteringforeach 循环未进入
【发布时间】:2017-10-22 20:44:20
【问题描述】:

我的目标是让国家名称按字母顺序打印出来。这是我为此编写的函数...

function getCountries(){
    $namesQ = 'SELECT Name FROM `country` ORDER BY Name ASC';
    global $myPdo;
    $command = $myPdo -> prepare('namesQ');
    $command -> execute();  
    return $command;    
}  

然后,我从 HTML 的数组中回显名称...

<!DOCTYPE html>

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Country Names</title>

        <link type="text/css" rel="stylesheet" href="primary.css" />
    </head>

    <body>
        <div id="main" action="controller.php" method="post">
            <?php
                $countries = getCountries();
                $countryNames = $countries->fetchAll();

                foreach( $countryNames as $countryName )
                {
                    echo 'test';
                    echo '<p> ' . $countryName['Name'] . '</p>';
                }
            ?>
        </div>
    </body>
</html>

但似乎根本无法访问foreach 循环,因为即使...

 echo 'test';

... 不打印到屏幕上。

我将$countryName 中的索引更改为fhsdjk,因为没有这样的索引,但我什至没有收到错误消息或任何东西。如何将echoforeach 循环内的任何内容中取出?

【问题讨论】:

  • 你需要传递变量的密码字符串 $command = $myPdo -> prepare($namesQ);

标签: php sql loops debugging foreach


【解决方案1】:

看来,您正在准备字符串'namesQ',但实际上您要准备分配给$namesQ 的sql 语句。所以,替换

$command = $myPdo->prepare('namesQ');

$command = $myPdo->prepare($namesQ);

我建议您将fetchAll() 调用包含在getCountries() 函数中,然后直接调用:

$countryNames = getCountries();

而且,由于您在发现 db-access 错误时遇到了一些问题,因此我建议您始终实施异常处理。特别是当您使用PDO 作为数据访问抽象时。这是一个示例 - 与您的代码类似:

function getCountries() {
    try {
        $namesQ = 'SELECT Name FROM `country` ORDER BY Name ASC';

        global $myPdo;

        // Hier: replaced 'namesQ' with $namesQ.
        $command = $myPdo->prepare($namesQ);

        if (!$command) {
            throw new Exception('The SQL statement can not be prepared!');
        }

        if (!$command->execute()) {
            throw new Exception('The PDO statement can not be executed!');
        }

        return $command->fetchAll();
    } catch (PDOException $pdoException) {
        echo '<pre>' . print_r($pdoException, true) . '</pre>';
        exit();
    } catch (Exception $exception) {
        echo '<pre>' . print_r($exception, true) . '</pre>';
        exit();
    }
}

也许我的早期答案,关于异常处理,也会有所帮助:

Exception handling for PDO::prepare() and PDOStatement::execute() + A generalized exception handling scheme

【讨论】:

    【解决方案2】:

    你的传递字符串你需要传递变量

    $command = $myPdo -> prepare('namesQ');
    (To)
    $command = $myPdo->prepare($namesQ);
    

    【讨论】:

      猜你喜欢
      • 2014-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-23
      • 1970-01-01
      • 2020-08-03
      • 2021-11-09
      相关资源
      最近更新 更多