user3569641
user3569641

Reputation: 922

Fetching Data from DB using PDO with Class

Why is it that only the first sets of data are displayed and not the entire data?

Here is my code..(Sorry, still new to OOP)

include 'crud.php';

$db_host = "localhost";
$db_name = "crud";
$db_username = "root";
$db_password = "";

$conn = new PDO("mysql:host=$db_host;dbname=$db_name", $db_username, $db_password);


$select = new Crud($conn);
$select->crud_select();

crud.php

class Crud
{
    private $conn;
    public function __construct($conn){
        $this->conn = $conn;
    }
    public function crud_insert($lname, $fname, $address, $age){

    }
    public function crud_select(){
        $result = $this->conn->prepare("SELECT * FROM personal_info");
        $result->execute();
        $count = $result->rowCount();
        if($count == 0){
            $no_files = "No file(s) found!";
            echo $no_files;
        }
        else{
            $row = $result->fetch();
            echo $row['last_name'] . "<br/>";
            echo $row['first_name'] . "<br/>";
            echo $row['address'] . "<br/>";
            echo $row['age'] . "<br/>";
        }   
    }
}

if i'm trying fetchAll() it's not displaying anything.

Upvotes: 0

Views: 224

Answers (2)

Vijayaragavendran
Vijayaragavendran

Reputation: 703

you should place the fetch in while loop to get all the results printed

while($row = $result->fetch())
{
            echo $row['last_name'] . "<br/>";
            echo $row['first_name'] . "<br/>";
            echo $row['address'] . "<br/>";
            echo $row['age'] . "<br/>";
}

Upvotes: 2

Awlad Liton
Awlad Liton

Reputation: 9351

because you have fetch only one row. If you wanted to fetch multiple rows then you need a loop

        $result->execute();

        $count = $result->rowCount();
        $result->setFetchMode(PDO::FETCH_ASSOC);
        if($count == 0){
            $no_files = "No file(s) found!";
            echo $no_files;
        }

  else{
    while($row = $result->fetch()){
                echo $row['last_name'] . "<br/>";
                echo $row['first_name'] . "<br/>";
                echo $row['address'] . "<br/>";
                echo $row['age'] . "<br/>";     
     }
    }

or you can fetch array like this:

        $result->execute();        
        $count = $result->rowCount();

        if($count == 0){
            $no_files = "No file(s) found!";
            echo $no_files;
        }

  else{

        $resultset = $datas->fetchALL(PDO::FETCH_ASSOC);
        foreach($resultset as $row){
                    echo $row['last_name'] . "<br/>";
                    echo $row['first_name'] . "<br/>";
                    echo $row['address'] . "<br/>";
                    echo $row['age'] . "<br/>";     
         }
        }

Upvotes: 1

Related Questions