我剛開始使用OOP,並同時使用教程中,我遇到了以下錯誤:OOP PHP錯誤而查詢的MySQL
Warning: Missing argument 2 for MySQLDatabase::query(), called in
/Applications/MAMP/htdocs/object-oriented/public/index.php on line 7 and defined in
/Applications/MAMP/htdocs/object-oriented/includes/database.php on line 28
Notice: Undefined variable: sql in
/Applications/MAMP/htdocs/object-oriented/includes/database.php on line 29
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in
/Applications/MAMP/htdocs/object-oriented/includes/database.php on line 29
這裏是我的database.php中
<?php
require('config.php');
class MySQLDatabase {
public $connection;
public function open_connection() {
$this->$connection = mysqli_connect('DB_SERVER', 'DB_USER', 'DB_PASS');
if (!$this->connection) {
die("Database connection failed");
} else {
$db_select = mysqli_select_db($this->connection, DB_NAME);
if (!$select_db) {
die("Database selection failed");
}
}
}
public function close_connection() {
if (isset($this->connection)) {
mysqli_close($this->connection);
unset($this->connection);
}
}
public function query($connection, $sql) {
$result = mysqli_query($this->connection, $sql);
$this->confirm_query($result);
return $result;
}
和我index.php我試圖測試query()方法。
$sql = "INSERT INTO users (id, username, password, first_name, last_name) ";
$sql .= "VALUES (1, 'andrei', 'password', 'Andrei', 'Popa')";
$result = $database->query($sql);
$sql = "SELECT * FROM users WHERE id = 1";
$result_set = $database->query($sql);
$found_user = mysqli_fetch_array($result_set);
echo "Found user!" . $found_user['username'];
任何想法我做錯了什麼?謝謝
你的查詢功能需要兩個參數。你傳遞了一個 - 雖然你不需要傳遞'$ connection',因爲它從來沒有用過(你使用的是對象的$ connection屬性) – andrewsi
閱讀錯誤消息,它們看起來相當清晰 – 2013-12-16 19:42:43