将while循环更改为foreach

时间:2017-05-25 07:42:38

标签: php

我是PHP的新手,仍然习惯于语法。有人能告诉我如何重新编写这个块作为foreach而不是while循环吗?

当运行一个返回两行的SQL查询时,我只得到一个,我认为这与我正在使用的循环类型有关。

我无法获得有效的语法。

$stmt = $conn->prepare("SELECT * FROM `staff_details` WHERE first_name='{$_POST['firstname']}' AND surname='{$_POST['lastname']}'");
<?php while( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) { ?>
<tr>
    <td><?php echo $row['role']; ?></td>
    <td><?php echo $row['grade']; ?></td>
</tr>

谢谢

2 个答案:

答案 0 :(得分:1)

$stmt = $conn->prepare("SELECT * FROM `staff_details` WHERE first_name= ? AND surname= ?");
$stmt->execute(array($_POST['firstname'], $_POST['lastname'])); //prepare statements
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);

foreach ($row as $r){
            echo '<tr>';
            echo '<td>' . $r['role'] . '</td>';
            echo '<td>' . $r['grade'] . '</td>';
            echo '</tr>';
}

答案 1 :(得分:0)

$q = "SELECT * FROM `staff_details` WHERE first_name='{$_POST['firstname']}' AND surname='{$_POST['lastname']}'";
$result = $db->query($q)->fetchall(PDO::FETCH_ASSOC);
foreach ($result as $key) :
//do some actions
endforeach;