Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
433 views
in Technique[技术] by (71.8m points)

php - mysqli_query() expects parameter 1 to be mysqli, object given

I'm trying to create a class which can be used for connecting to MySQL database. This is my code:

The class:

<?php

class createCon  {
    var $host = 'localhost';
    var $user = 'root';
    var $pass = '';
    var $db = 'example';
    var $myconn;

    function connect() {
        $con = mysqli_connect($this->host, $this->user, $this->pass, $this->db);
        if (!$con) {
            die('Could not connect to database!');
        } else {
            $this->myconn = $con;
            echo 'Connection established!';}
        return $this->myconn;
    }

    function close() {
        mysqli_close($myconn);
        echo 'Connection closed!';
    }

}

And this is where I try to query the database:

<?php

include 'connect.php';

$connection = new createCon();
$connection->connect();

$query = 'SELECT * FROM  `nickname`';
$result = mysqli_query($connection, $query);

if($numrows = mysqli_num_rows($result)) {
    echo $numrows;
    while ($row = mysqli_fetch_assoc($result)) {
        $dbusername = $row['nick'];
        $dbpassword = $row['pass'];
        echo $dbusername;
        echo $dbpassword;
    }
}

I get the following error when I try to make a query:

Warning: mysqli_query() expects parameter 1 to be mysqli, object given in C:wampwwwuppgift 1 kompleteringest.php on line 13

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You want to pass in $connection->myconn instead of $connection. As in:

$result = mysqli_query($connection->myconn, $query);

As it stands, you're passing in an instance of your class, rather than a mysqli, which is what the error messages are complaining about.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...