在foreach语句之后,PHP脚本不会回显

时间:2015-12-28 01:59:20

标签: php mysql pdo

我已经测试了几种解决方案,但未能找到正确的解决方案。我已经测试过增加可用内存,使用不同的循环,例如while和foreach。我查看了代码,看看我是否错过任何括号或括号都没有成功。下面是代码,foreach循环后的echo语句不起作用。向数据库中添加其他行是正确回显的,所以我不相信这是一个内存问题。

echo <<<_END
<br>
<h3>View or Edit Contacts for $customerName</h3>
    <div id="contactList">
        <!-- Drop down list for customer select and update runs showCustomer.js when customer is selected-->
        <form>
            <select name="contacts" onchange="showContacts(this.value)">
            <option value="">Select a Contact to View:</option>
_END;

try {
$stmt2 = $conn->prepare("SELECT contactID, contactTitle, contactLast FROM contacts"); 
$stmt2->execute();

//return option statement for each row of customers
    //while ($row2 = $stmt2->fetch()) {
    foreach($stmt2 as $row2){
        echo '<option value="'.$row2['contactID'].'">'.$row2['contactTitle']." ".$row2['contactLast']."</option><br>";
    }
    echo "<br>";
    echo "Finally Working";
    echo "<br>";
}

catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}

1 个答案:

答案 0 :(得分:4)

您在</select>之后错过了foreach

编辑如下:

foreach($stmt2 as $row2){
        echo '<option value="'.$row2['contactID'].'">'.$row2['contactTitle']." ".$row2['contactLast']."</option><br>";
}
echo '</select>'; // added this line
echo "<br>";
echo "Finally Working";
echo "<br>";

你会发现它是Finally Working

<小时/> 注意: 如果您检查页面,您可能会看到如下内容:

<option value="1">Select a Contact to View:</option>
<option value="2">Some Option</option>
<br>
finally working
<br>

在我的睾丸(firefox)上,浏览器会自动添加</select>,但仅在<br>Finally Working<br>之后。