PHP PDO使用类选择数据

时间:2017-02-14 05:03:33

标签: php class pdo

我在这里创建了一个用于获取数据的类,它工作正常,但我不知道它是否是正确的代码?任何人都可以为我检查代码吗?

<?php
class SingleData {
    public $tbName;
    public $id;
    public $col;
    public function viewData($tbName,$id,$col){
        $start = new PDO('mysql:host=localhost;dbname=user;charset=utf8mb4',"root","pass");
        $con = $start->prepare("SELECT $col FROM $tbName WHERE id=?");
        $con->bindValue(1, $id, PDO::PARAM_INT);
        $con->execute();
        $result=$con->fetchColumn();
        return $result;
    }
}
?>

这就是我调用数据的方式

$data=new SingleData;
echo $data->viewData('user',1,'FName'). " ";
echo $data->viewData('user',1,'LName'). </br>;
echo $data->viewData('user',1,'Job'). </br>;

,结果将是:

John Smith
Sales Manager

1 个答案:

答案 0 :(得分:-1)

就个人而言,我会按照以下方式做点什么:

class SingleData {
    private $_db;
    public $tbName, $id, $col;

    public function __construct(){
        try{
            $this->_db = new PDO("mysql:host=localhost;dbname=user;charset=utf8mb4", "root", "pass");
        } catch(e){
            die($e->getMessage());
        }
    }

    public function viewData($tbName, $id, $col){
        $con = $this->_db->prepare("SELECT $col FROM $tbName WHERE id=?");
        $con->bindValue(1, $id, PDO::PARAM_INT);
        $con->execute();

        $result=$con->fetchColumn();
        return $result;
    }
}