我得到了:
警告:mysqli_query()要求参数1为mysqli,在第35行的/Applications/XAMPP/xamppfiles/htdocs/parkgames0.2/private/database.php中给出null
当我运行index.php。
database.php如下:
<?php
require_once("config.php");
class MySQLDatabase {
private $connection;
function __constuct() {
$this->open_connection();
}
public function open_connection() {
// 1. Create a database connection
$this->connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS);
if(!$this->connection) {
die("Database connection failed: " . mysqli_error());
} else {
// 2. Select a database to use
$db_select = mysqli_select_db($this->connection, DB_NAME);
if(!$db_select) {
die("Database selection failed: " . mysql_error());
}
}
}
public function close_connection() {
// 5. Close connection (if exists)
if(isset($this->connection)) {
mysqli_close($this->connection);
unset($this->connection);
}
}
public function query($sql) {
$result = mysqli_query($this->connection, $sql);
$this->confirm_query($result);
return $result;
}
public function mysql_prep($value) {
$magic_quotes_active = get_magic_quotes_gpc();
$new_enough_php = function_exists( "mysql_real_escape_string" ); // i.e. PHP >= v4.3.0
if( $new_enough_php ) { // PHP v4.3.0 or higher
// undo any magic quote effects so mysql_real_escape_string can do the work
if( $magic_quotes_active ) { $value = stripslashes( $value ); }
$value = mysql_real_escape_string( $value );
} else { // before PHP v4.3.0
// if magic quotes aren't already on then add slashes manually
if( !$magic_quotes_active ) { $value = addslashes( $value ); }
// if magic quotes are active, then the slashes already exist
}
return $value;
}
private function confirm_query($result) {
if(!$result) {
die("Database query failed");
}
}
}
$database = new MySQLDatabase();
?>
index.php是:
require_once("../private/database.php");
if(isset($database)) { echo "true"; } else { echo "false";}
echo "<br>";
$query = "SELECT * ";
$query .= "FROM activities ";
$query .= "WHERE id=1";
$query .= " LIMIT 1";
echo $query;
$result = $database->query($query);
$found_activity = mysqli_fetch_array($result);
echo $found_activity["name"];
config.php只包含DB_SERVER,DB_USER,DB_PASS和DB_NAME的定义
答案 0 :(得分:0)
mysqli_connect在失败时不返回false。它总是返回一个对象。当它失败时会出错。因此,您必须检查该错误,而不是检查该对象是否存在。
public function open_connection() {
// 1. Create a database connection
$this->connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS);
if($this->connection->connect_error) {
die("Database connection failed: " . mysqli_error());
} else {
// 2. Select a database to use
$db_select = mysqli_select_db($this->connection, DB_NAME);
if(!$db_select) {
die("Database selection failed: " . mysql_error());
}
}
}