mysqli_query()期望参数1,我无法找到我做错的地方

时间:2015-04-22 07:16:20

标签: php mysqli

class AirData{
    function __construct() {
            $this->connect();
            echo "start";
    }


    function connect(){
        /*connect to data base change to PDO, for securely*/
        $connection = mysqli_connect('localhost', DB_USER, DB_PASS);

            if (!$connection) {
                die('Could not connect: ' . mysqli_error());
            }
            mysqli_set_charset($connection, 'utf8');
            $db_selected = mysqli_select_db($connection, DB_NAME);

            if (!$db_selected) {
                die('Can\'t use ' . DB_NAME . ': ' . mysqli_error());
            }
    }

    function insert($connection, $table, $fields, $values){
        $fields = implode(", ", $fields);
        $values = implode("','", $values);
        $sql="INSERT INTO $table(ID, $fields) VALUES ('', '$values')";

       /*error here something is wrong at here*/
        if(!mysqli_query($connection,$sql)){
            die('could not connect');
        } else {
            return TRUE;
        }
    }
}

$ALIST = new AirData;

我无法找到我做错了什么,我切换$ connection和$ sql,仍然无法正常工作,mysqli_query()期望参数1为mysqli,null为。

任何人都可以帮我看看吗?

2 个答案:

答案 0 :(得分:2)

声明一个将存储连接的私有变量。在课堂内使用它。无需通过函数传递它。试试 -

class AirData{

    private $connection;
    function __construct() {
            $this->connect();
            echo "start";
    }


    function connect(){
        /*connect to data base change to PDO, for securely*/
        $this->connection = mysqli_connect('localhost', DB_USER, DB_PASS);

            if (!$this->connection) {
                die('Could not connect: ' . mysqli_error());
            }
            mysqli_set_charset($this->connection, 'utf8');
            $db_selected = mysqli_select_db($this->connection, DB_NAME);

            if (!$db_selected) {
                die('Can\'t use ' . DB_NAME . ': ' . mysqli_error());
            }
    }

    function insert($table, $fields, $values){
        $fields = implode(", ", $fields);
        $values = implode("','", $values);
        $sql="INSERT INTO $table(ID, $fields) VALUES ('', '$values')";

       /*error here something is wrong at here*/
        if(!mysqli_query($this->connection,$sql)){
            die('could not connect');
        } else {
            return TRUE;
        }
    }
}

答案 1 :(得分:-2)

请检查您的插入查询。您的查询无法正常工作,因此请检查它。     你可以尝试查询

 $sql="INSERT INTO $table(ID, '$fields') VALUES ('', '$values')";