本文介绍了如何使用PDO在PHP中打印MySQL数据库表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打印表上的所有行.每行都是论坛中问题的答案.用户可以删除行.

I want to print all the rows on the table. Every row is an answer to a question in a forum. The user can delete rows.

我可以在数据库中获取整个表.但是我不知道如何获得每一行.

I can get the whole table in the database. But i don't know how to get every row.

控制器:

for ($idAnswer=1; $idAnswer<=?; $idAnswer++){
    $data=getData($idCourse, $idForum, $idAnswer);
    $author=$data['author'];
    $answer=$data['answer'];
    $date=$data['date'];
    echo $author;
    echo $answer;
    echo $date;
    }

功能:

public function getData($idCourse, $idForum, $idAnswer) {
        //Conect
        try {
            $this->BD=new PDO($this->infoBD, $this->usuarioBD, $this->claveBD);
            $this->BD->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            }catch(PDOException $e){echo $e; }
        //Get data

            try {
                $sql=$this->BD->prepare("SELECT author, date, answer
                FROM   answers
                WHERE  idForum='$idForum' and idCourse='$idCourse' and idAnswer='$idAnswer'");
                $sql->execute();
                $sql->setFetchMode(PDO::FETCH_ASSOC);
                $data=$sql->fetch();
                if ($data!=null){
                return $data;
                } else {
                    return 0;
                }
            }catch (PDOException $e){
                echo $e;
            }

感谢您的帮助

推荐答案

fetch()函数将返回结果集中的下一行.您需要这样的东西才能获得所有结果:

fetch() function returns you the next row from the result set. You need something like this to get all results:

while($data = $sql->fetch()) {
   echo ($data['author']);
   echo ($data['date']);
   //...etc...
}

或者您可以使用 fetchAll()函数,该函数返回结果中每一行的数组,并且可以使用循环顶部遍历该数组并对每一行执行任何操作.

Or you can use fetchAll() function which returns an array with each row from the result and you can use a loop top traverse the array and do whatever you want with each row.

具有 fetchAll()的示例:

$data = $sql->fetchAll(PDO::FETCH_ASSOC);
foreach($data as $row) {
   echo $row['autor'];
   echo $row['date'];
  //do whatever you want with the row
}

这篇关于如何使用PDO在PHP中打印MySQL数据库表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 09:41