简体   繁体   中英

Use of MySQLi within a class

function __construct(mysqli $db, $country = NULL, $sport = NULL) {
    $this->db = $db;
    $this->country = base64_decode($country);
    $this->sport = base64_decode($sport);
}

public function GetColor($colorcode) {
    $query = 'SELECT naam_nl FROM colors WHERE code = $colorcode';
    $result = $this->db->query($query);
    while ($row = $result->fetch_assoc()) { // Line 21
        echo $row['naam_nl'];
    }
    $result->close();
}

Gives me:

Fatal error: Call to a member function fetch_assoc() on a non-object in /home/cloud/public/td/teamdresser.class.php on line 21

So I tried:

    $result = $this->db->query($query);
    while ($row = $this->db->fetch_assoc($result)) {
        echo $row['naam_nl'];
    }

And then...

Fatal error: Call to undefined method mysqli::fetch_assoc() in /home/cloud/public/td/teamdresser.class.php on line 21

I'm doing something wrong.. Can someone point me in the right direction?

This part is wrong:

public function GetColor($colorcode) {
    $query = 'SELECT naam_nl FROM colors WHERE code = $colorcode';

PHP won't interpolate $colorcode when using single quotes. Use double quotes intead:

$query = "SELECT naam_nl FROM colors WHERE code = $colorcode";

Comments :

  • Always check for the return value! That makes spotting errors much easier.

  • Why don't you use prepared statements?

Like the comments say, you need to do some error checking:

public function GetColor($colorcode) {
    $query = 'SELECT naam_nl FROM colors WHERE code = $colorcode';
    $result = $this->db->query($query);
    if ($result === false) {
        // Throw or handle an error here
    } else {
        while ($row = $result->fetch_assoc()) { // Line 21
            echo $row['naam_nl'];
        }
        $result->close();
    }
}

Additionally, you need the mysqlnd drivers: Fatal error: Call to undefined method mysqli_result::fetch_all()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM