2017-05-23 92 views
-1

我的目标是让国家名称按字母顺序打印出来。这是我写的功能...foreach循环不进入

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,因为没有这样的索引,但我甚至没有收到任何错误消息或任何内容。我怎样才能得到echo出什么foreach循环内?

+0

您passig字符串你需要传递varibale $ command = $ myPdo - > prepare($ namesQ); – JYoThI

回答

1

您的通过字符串你需要传递变量

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

看来,你是准备串'namesQ',但实际上你要准备分配给$namesQ的SQL语句。因此,更换

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

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

我建议你到包括fetchAll()呼叫到getCountries()功能,并只要致电:

$countryNames = getCountries(); 

而且,由于你有一些问题发现数据库访问错误,我建议你总是实现异常处理。特别是当您使用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