gpt4 book ai didi

php - fatal error : Uncaught Error ( php mysql )

转载 作者:行者123 更新时间:2023-11-30 22:04:51 25 4
gpt4 key购买 nike

我正在使用 mysql 学习 php 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);
}

}

Fatal error: Uncaught Error: Call to a member function prepare() on null in C:\MAMP\htdocs\Practice\databasesclass.php:31 Stack trace: #0 C:\MAMP\htdocs\Practice\index.php(7): Database->query('SELECT * FROM u...') #1 {main} thrown in C:\MAMP\htdocs\Practice\databasesclass.php on line 31

第 31 行是:

$this->stmt = $this->dbh->prepare($query);

最佳答案

无需将 $this->user$this->pass 传递到您的 $dns 变量中。从那里删除它们。

所以 $dns 变量将是

来自

$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname . $this->user . $this->pass;

$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;

如果您发现任何错误,请检查并告诉我。

关于php - fatal error : Uncaught Error ( php mysql ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42132215/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com