我正在尝试从程序PHP切换到OO PHP。
我创建了一个看起来像这样的Db类:
class Db {
protected static $connection;
/*
Attempt to connect to database.
@Return bool false on failure, mysqli object instance on success
*/
public function connect() {
if(!isset(self::$connection)) {
//Parse DB info from configuration file
$config = parse_ini_file('../validconfigpath/config.ini');
//Attempt to connect to the datbase
self::$connection = new mysqli($config['dbhost'], $config['dbuser'], $config['dbpass'], $config['dbname']);
if(self::$connection === false) {
//Database connection unsuccessful, how to handle?
echo "Error connecting to database.<br />";
return false;
}
return self::$connection;
}
}
/*
* Query the database
* @param $query The sql string
* @return mixed The result of the mysqli::query() function
*/
public function query($query) {
//Connect to the database
$connection = $this -> connect();
//Query the database
$result = $connection -> query($query);
return $result;
}
/*
* Fetch rows from the database (SELECT query)
* @param $query The query string
* @return bool false on failure / array Database rows on success
*
*/
public function select($query) {
$rows = array();
$result = $this -> query($query);
if ($result === false) {
return false;
}
while($row = $result -> fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
/*
* Fetch last inserted ID from the database
* @return ID of last inserted record using this connection, or 0 if no INSERT or UPDATE statements were sent
*/
public function inserted_id() {
$connection = $this -> connect();
return $connection -> insert_id;
}
public function quote($value) {
$connection = $this -> connect();
return "'" . $connection -> real_escape_string($value) . "'";
}
}
我正在尝试使用以下代码测试quote
函数:
include_once 'Classes/DB.php';
$db = new Db();
$firstName = $db -> quote("First");
echo $firstName. "<br />";
$lastName = $db -> quote("Last");
echo $lastName. "<br />";
我得到了$firstName
的预期输出,如下所示:
'First'
但是对于我$lastName
的第二个输出,我得到了:
Fatal error: Uncaught Error: Call to a member function real_escape_string() on null in ..\Classes\DB.php:91 Stack trace: #0 ..\index.php(11): Db->quote('Last') #1 {main} thrown in ..\Classes\DB.php on line 91
我尽可能地告诉$connection
发生了一些事情,但我无法弄清楚connect()
出了什么问题。
此外,我认为最好在__construct
中创建一个连接?
答案 0 :(得分:3)
connect()方法中存在错误。此方法仅返回第一个连接实例。对connect()的第二次调用将返回null。尝试移动return self :: $ connection;到这个方法的最后一行。
public function connect()
{
if (!isset(self::$connection)) {
//Parse DB info from configuration file
$config = parse_ini_file('../validconfigpath/config.ini');
//Attempt to connect to the datbase
self::$connection = new mysqli($config['dbhost'], $config['dbuser'], $config['dbpass'], $config['dbname']);
if (self::$connection === false) {
//Database connection unsuccessful, how to handle?
echo "Error connecting to database.<br />";
return false;
}
}
return self::$connection;
}