gpt4 book ai didi

php - 使用 PDO 对 null 调用成员函数 query()

转载 作者:行者123 更新时间:2023-11-29 11:38:28 26 4
gpt4 key购买 nike

我刚刚检查了 stackoverflow 上提供的所有答案,它们很相似,但不完全是我的答案。因此,请不要将此帖子视为重复。

这些是我执行时的代码

Fatal error: Call to a member function query() on null in C:\wamp64\www\ourCMS\index.php on line 12

这是我的片段:

<?php

class DB
{
private $dbHost;
private $dbName;
private $dbUser;
private $dbPass;

protected $con;

function set_db($host, $db, $user, $pass)
{
$this->dbHost = $host;
$this->dbName = $db;
$this->dbUser = $user;
$this->dbPass = $pass;

}

function connect()
{
$info = 'mysql:host='.$this->dbHost.';dbname='.$this->dbName;
try
{
$this->con = new PDO($info, $this->dbUser, $this->dbPass);
}
catch(PDOException $e)
{
print "Error Founds: ".$e->getMessage().PHP_EOL;
die();
}
}
}

// here is the place where i'm trying to use this actually
if (isset($_POST['submit']))
{
include('include/database.php');

$database = new DB;
$database->set_db("localhost", "ourcms", "root", "");
$conn = $database->connect();

$name = $_POST['nm'];
$query = "INSERT INTO testingpdo (name) VALUES ('$name')";
$data = $conn->query($query);
$result = $data->fetchAll(PDO::FETCH_ASSOC);

print_r($result);
}

最佳答案

您不会从 DB::connect ($conn = $database->connect();) 返回任何内容。在函数末尾添加 return $this->con;

function connect()
{
$info = 'mysql:host='.$this->dbHost.';dbname='.$this->dbName;
try
{
$this->con = new PDO($info, $this->dbUser, $this->dbPass);
}
catch(PDOException $e)
{
print "Error Founds: ".$e->getMessage().PHP_EOL;
die();
}
return $this->con;
}

关于php - 使用 PDO 对 null 调用成员函数 query(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36238263/

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