Search code examples
phpmysqldatabaseforum

How to print a MySQL database table in PHP using PDO


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


Solution

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