Search code examples
phpmysqloopmysqliintegrate

OOP PHP integrate mysqli_query


Im gonna edit the question to make it clearer, so you can see what i have got now, and get an easier understanding of the problem.

<?php
$mysqli = new mysqli("localhost", "user", "password", "test");
class building
{
private $mysqli;
public $buildingid;
public $userid;
public $buildinglevel;




public function __construct($buildingid, $userid, \mysqli $mysqli)
{
    $this->buildinglevel;
    $this->mysqli = $mysqli;
}

public function getLevel()
{
    return $this->mysqli->query("SELECT ".$this->buildingid." FROM worlds WHERE city_userid=".$this->userid."");
}
}

}
?>

Then I use this to create and use the function:

$cityHall = new building("cityHall",$user['id'],$mysqli);
echo $cityHall->getLevel();

This turns out blank, and nothing happens.


Solution

  • You should inject instance of mysqli to __construct() of building class:

    $mysqli = new mysqli('user', 'password', 'localhost', 'test');

    if ($mysqli->connect_errno) { printf("Connect failed: %s\n", $mysqli->connect_error); }

    class building
    {
    private $mysql;
    private $buildingid;
    private $userid;
    
    // I need to have a mysqli_query here to get the info for the correct building, 
    //to be able to set the "buildinglevel" for each object from the MYSQL DB, seems basic   
    //but none of the things ive tried has worked.
    
    
    public function __construct($buildingid, $userid, $mysqli)
    {
        $this->buildinglevel;
        $this->mysqli = $mysqli;
        $this->userid = (int)$userid;
        $this->buildingid= (int)$buildingid;
    }
    
    public function getLevel()
    {
        $query = $this->mysqli->query("SELECT ".$this->buildingid." FROM worlds WHERE city_userid=".$this->userid);
        $row = $query->fetch_assoc();
        if (!$query) {
            return $this->mysqli->error;
        }
        if ($query->num_rows == 0) {
            return 'no database records found';
        }
    
        return $row;
    }
    
    }
    
    $Bulding = new building("cityHall", $user['id'], $mysqli);
    $level = $Bulding->getLevel();
    var_dump($level);