0

嘿伙计们,我正在用 php 学习 OOP。当我尝试在自己的班级中自定义 PDO 时,我遇到了一些问题。基本上我试图返回该行并在我的班级之外获取它。不幸的是我不会工作。我收到此错误“调用非对象上的成员函数 fetch()”。如果可以的话,看看并给我一些提示。非常感谢。

$connection = new MySql(DBUSER, DBPASS);
$row = $connection->query("select * from users", "name");
while($row->fetch(PDO::FETCH_ASSOC)){
    echo "<p>". $row["name"] ."</p>";
}

这是 MySql 类的样子:

class MySql{
    private $dbc;
    private $user;
    private $pass;

    function __construct($user="root", $pass=""){
    $this->user = $user;
    $this->pass = $pass;    
    try{
       $this->dbc = new PDO("mysql:host=localhost; dbname=DBNAME;charset=utf8", $user, $pass);
        }
    catch(PDOException $e){
       echo $e->getMessage();
       echo "Problem z Połączeniem do MySql sprawdź haslo i uzytkownika";
        }
    }
    public function query($query, $c1=""){
    $mysqlquery = $this->dbc->prepare($query);
    $mysqlquery->execute();
    return $row = $mysqlquery->fetch(PDO::FETCH_ASSOC);
    /* I WANT TO PERFORM COMENTED CODE OUTSIDE THE CLASS
    while($row = $mysqlquery->fetch(PDO::FETCH_ASSOC)){
        if($c1!=""){
        echo "<p>". $row[$c1] ."</p>";
        }
    }
    */
}
4

1 回答 1

1

如果你想返回$mysqlquery迭代它,你必须返回$mysqlquery,而不仅仅是一行。

这是您的课程的更好版本,显着改进了错误处理和安全性。但仍然糟糕的可配置性。

class MySql{
    private $dbc;

    function __construct($user="root", $pass=""){
        $dsn = "mysql:host=localhost; dbname=DBNAME;charset=utf8";
        $opt = array(
           PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
           PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        );
       $this->dbc = new PDO($dsn, $user, $pass, $opt);
    }
    public function query($query, $data = array()){
        $stm = $this->dbc->prepare($query);
        $stm->execute($data);
        return $stm;
    }
}

$connection = new MySql(DBUSER, DBPASS);
$stm = $connection->query("select * from users WHERE name = ?", array("name"));
while($row = $stm->fetch()){
    echo "<p>". $row["name"] ."</p>";
}
于 2013-08-04T09:12:40.303 回答