如何选择2列不同的id

时间:2018-02-06 08:09:38

标签: php mysql sql pdo

我想显示具有不同标题的所有列(课程)

我有一个名为course

的表
|---------- id -----------|------ id_user ----|----title_course---|

|.......... 1 ............|....... 5  ........|...... title1 .....|

|.......... 2 ............|.......7  .........|...... title2 .....|

|.......... 3 ............|....... 9  ........|...... title3 .....|

当我运行此代码时

<?php 
$stmt = $connect->query(" SELECT * FROM course ");

while ($row = $stmt->fetch()) 
{
?> 
     <div class="all" > <?php echo $row['title_course']; ?>  </div>
<?php } ?>

问题是它始终显示

title3

结果:

<div class="all" > title3  </div>
<div class="all" > title3  </div>
<div class="all" > title3  </div>

3 个答案:

答案 0 :(得分:1)

PDOStatement :: execute - 执行准备好的声明

PDOStatement :: fetch - 从结果集中获取下一行

PDOStatement :: fetchAll - 返回包含所有结果集行的数组

PDOStatement :: fetchColumn - 从结果集的下一行返回单个列

<?php
$stmt = $connect->prepare("SELECT * FROM course");
$stmt->execute();

/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $stmt->fetchAll();

foreach ($result as $res) {
  print_r($res);
}
?>

答案 1 :(得分:0)

正如@Sinto所说 使用fetchAll()获取所有结果,然后遍历结果集

答案 2 :(得分:0)

不工作总是显示最后结果

<?php 
$stmt = $connect->prepare(" SELECT * FROM course ");
$stmt->execute();
$mae = $stmt->fetchAll() ;
foreach ($mae as $row ) { ?>
  <div> print_r($row['id_user']); </div>
  <div> print_r($row['id_user']); </div>
  <div> print_r($row['id_user']); </div>
<?php } ?> 

结果

<div> 9 </div>
<div> 9 </div>
<div> 9 </div>