Php 致命错误:对非对象调用成员函数getOne()
我是php oop新手。在这里,我想使用singleton类进行数据库连接,但遇到如下错误: 致命错误:对C:\xampp\htdocs\singleton\new\singleton\u db.php中的非对象调用成员函数getOne() 这里我给出了两个文件 1.singleton_db.phpPhp 致命错误:对非对象调用成员函数getOne(),php,Php,我是php oop新手。在这里,我想使用singleton类进行数据库连接,但遇到如下错误: 致命错误:对C:\xampp\htdocs\singleton\new\singleton\u db.php中的非对象调用成员函数getOne() 这里我给出了两个文件 1.singleton_db.php <?php class database { public $query; public $results;
<?php
class database
{
public $query;
public $results;
public $conn;
public static $database;
//connect to the database
public function __construct()
{
$this->conn = mysql_connect('localhost','root','');
if ($this->conn)
{
mysql_select_db('test1');
}
}
public static function instance()
{
if (!isset(self::$database)) {
self::$database = new database();
}
return self::$database;
}
function getOne($sql) {
$result = $this->conn->getOne($sql); //Error in this line
if(database::isError($result)) {
throw new Exception($result->getMessage(), $result->getCode());
}
return $result;
}
function startTransaction() {
//autoCommit returns true/false if the command succeeds
return $this->conn->autoCommit(false);
}
function commit() {
$result = $this->conn->commit();
if(database::isError($result)) {
throw new Exception($result->getMessage(), $result->getCode());
}
$this->conn->autoCommit(true);
return true;
}
function abort() {
$result = $this->conn->rollback();
if(database::isError($result)) {
throw new Exception($result->getMessage(), $result->getCode());
}
return true;
}
//returns numerically indexed 1D array of values from the first column
public function insert($table, $arFieldValues) {
$fields = array_keys($arFieldValues);
$values = array_values($arFieldValues);
// Create a useful array of values
// that will be imploded to be the
// VALUES clause of the insert statement.
// Run the mysql_real_escape_string function on those
// values that are something other than numeric.
$escVals = array();
foreach($values as $val) {
if(! is_numeric($val)) {
//make sure the values are properly escaped
$val = "'" . mysql_real_escape_string($val) . "'";
}
$escVals[] = $val;
}
//generate the SQL statement
$sql = " INSERT INTO $table (";
$sql .= join(', ', $fields);
$sql .= ') VALUES(';
$sql .= join(', ', $escVals);
$sql .= ')';
$hRes = mysql_query($sql);
if(! is_resource($hRes)) {
$err = mysql_error($this->conn) . "\n" . $sql;
throw new Exception($err);
}
return mysql_affected_rows($hRes);
}
}
我能做些什么来修复此问题?您的问题是尚未定义
getOne();
方法正确。财产
$this->conn
只是mysql_connect()函数的结果,该函数是“成功时为mysql链接标识符,失败时为FALSE”。它不是一个对象,因此,您不能向它索取getOne();方法。既然PHP已经以MySQLI和PDO的形式提供了非常好的数据库类,为什么还要实现自己的数据库类?
$this->conn