查询mysql时出现OOP PHP错误

时间:2013-12-16 19:40:28

标签: php mysql oop

我刚开始使用OOP,在使用教程时遇到了以下错误:

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'];

知道我做错了什么吗?感谢

3 个答案:

答案 0 :(得分:1)

public function query($connection, $sql) {

您不需要第一个参数,因为连接是您的类的属性。因此,只需将$sql传递给查询方法,就像使用方法时一样:

public function query($sql) {

答案 1 :(得分:1)

这是你的定义:

public function query($connection, $sql) {

这是你的电话:

$result = $database->query($sql);

您需要添加连接:)

答案 2 :(得分:0)

您有很多错误:

<强>第一

$db_select = mysqli_select_db($this->connection, DB_NAME);
if (!$select_db) {

检查varibables db_selectselect_db

<强>第二

public function query($connection, $sql) {

$result = $database->query($sql);

你需要检查你的论点。我想,您需要从声明中删除$ connection

public function query($sql) {

因为接下来你正在使用类变量:

$this->connection;

<强>第三

public function open_connection()

您班级中没有counstructor而且您不会调用方法open_connection,因此:您的有效连接是NULL

您需要将此方法添加到您的课程中:

function __construct() {
    open_connection();
}