使用带有类的PDO从数据库中获取数据

时间:2014-06-27 13:25:01

标签: php mysql pdo

为什么只显示第一组数据而不显示整个数据?

这是我的代码..(对不起,对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/>";
        }   
    }
}

如果我尝试fetchAll()它没有显示任何内容。

2 个答案:

答案 0 :(得分:2)

你应该把fetch放在while循环中以打印所有结果

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

答案 1 :(得分:1)

因为你只获取了一行。如果你想获取多行,那么你需要一个循环

        $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/>";     
     }
    }

或者您可以像这样获取数组:

        $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/>";     
         }
        }