我正在使用php
学习mysql
oop,我无法修复此代码。
我已经检查了两次并检查了这个平台以确认。
<?php
require 'databasesclass.php';
$database = new Database();
$database->query('SELECT * FROM users');
$rows = $database->resultset();
print_r($rows);
,我的数据库类
<?php
class Database{
private $host = 'localhost:8889';
private $user = 'root';
private $pass = 'root';
private $dbname = 'register';
private $dbh;
private $error;
private $stmt;
public function __construct(){
// Set the DSN
$dsn = 'mysql:host='. $this->host . ';dbname=' . $this->dbname . $this->user . $this->pass;
// set options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION );
try {
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
} catch (PDOException $e) {
$this->error = $e->getMessage();
}
}
public function query($query){
$this->stmt = $this->dbh->prepare($query);
}
public function bind($pram, $value, $type = null){
if (is_null($type)){
switch(true) {
case is_int($value):
$type = PDO::PRAM_INT;
break;
case is_bool($value):
$type = PDO::PRAM_BOOL;
break;
case is_null($value):
$type = PDO::PRAM_NULL;
break;
default:
$type = PDO::PRAM_STR;
}
}
$this->stmt->bindValue($parm, $value, $type);
}
public function execute(){
return $this->stmt->execute();
}
public function resultset(){
$this->execute();
return $this->stmt->fetchALL(PDO::FETCH_ASSOC);
}
}
致命错误:未捕获错误:调用成员函数prepare() null在C:\ MAMP \ htdocs \ Practice \ databasesclass.php中:31堆栈跟踪:#0 C:\ MAMP \ htdocs \ Practice \ index.php(7):Database-&gt; query(&#39; SELECT * FROM u ...&#39;)在C:\ MAMP \ htdocs \ Practice \ databasesclass.php中抛出#1 {main} 在第31行
第31行是:
$this->stmt = $this->dbh->prepare($query);
答案 0 :(得分:0)
在您执行$this->dbh
的那一刻,prepare
为空。在执行//Use tab as field separator
$sep = "\t";
$eol = "\n";
$fputcsv = count($headings) ? '"'. implode('"'.$sep.'"', $headings).'"'.$eol : '';
之前,您可以检查它是否是PDO的实例。
答案 1 :(得分:0)
无需将 $ this-&gt;用户和 $ this-&gt;传递传递到 $ dns 变量中。从那里删除它们。
所以 $ dns 变量将是
<强>从强>
XmlSerializer
以强>
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname . $this->user . $this->pass;
如果您发现任何错误,请检查并告诉我。