How to print a MySQL database table in PHP using PDO [closed]

风流意气都作罢 提交于 2020-01-07 05:49:06

问题


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.

The controller:

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;
    }

The funtion:

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;
            }

Thanks for your help


回答1:


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...
}

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.

Example with fetchAll():

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



回答2:


Use fetchall(PDO::FETCH_ASSOC)



来源:https://stackoverflow.com/questions/29655369/how-to-print-a-mysql-database-table-in-php-using-pdo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!