Skip to content
Advertisement

PHP code convert to PHP/MySQLi OOP

today i tried to convert my code to PHP/MySQLi OOP code.

class Database
{
private $host;
private $user;
private $password;
private $db;
private $mysqli;

function __construct()
{
    $this->host = "*****";
    $this->user = "*****";
    $this->password = "******";
    $this->db = "*****";

    $this->mysqli = new mysqli($this->host, $this->user, $this->password, $this->db);

    if (mysqli_connect_errno()):
        printf("Connect failed: %sn", mysqli_connect_error());
        exit();
    endif;
}
}

This is a script for the query’s:

include_once("WD_Config/database.php");

class Adressen_Db
{
function __construct()
{
    $this->database = new Database();
}

public function selecteer()
{
    $query = "SELECT * FROM wd_adressen WHERE verborgen = 0 ORDER BY naam ASC";
    $result = $this->database->mysqli->query($query);

    return $result;
}
}

And this is how i call it.

$adressen = new Adressen_Db;
$adressen_result = $adressen->selecteer();

echo "<p>";
while ($row = $adressen_result->fetch_assoc()):
echo "<a href='http://maps.google.com/?q=".$row['voladres']."'     target='_blank'>".$row['naam']."</a> woonachtig op <i>".$row['voladres']."</i><br>";
endwhile;
echo "</p>";

I alway get a “Call to a member function query() on a non-object”. Doesn’t matter what i trie …

Can somebody tell me why that is?

Thanks!

Advertisement

Answer

I think while you definitely need to have $mysqli as public so it can be accessed in the other method, there might be something else, as the error would be something like

trying to access private property in database class

or something like that, whereas your script throws a non-object call error

I think your new Adressen_Db; lacks the parenthesis:

$adressen = new Adressen_Db();
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement