Cevil Cevil - 6 months ago 44
SQL Question

Trying to create php class for mysqli connection and use for query.

So I'm trying to create a class which can be used for connecting to mysql database. Should'nt be to advanced and it's all fun and games until i try to use my class. 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 errors when I try to make a query:

( ! ) Warning: mysqli_query() expects parameter 1 to be mysqli, object given in C:\wamp\www\uppgift 1 kompletering\test.php on line 13

( ! ) Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null given in C:\wamp\www\uppgift 1 kompletering\test.php on line 15


I think i kind of understand why i get the errors, however i have no clue what so ever how to fix it. Tried a million things and nothing works. I am very new to OOP and php and would greatly appriciate some advice!

Answer

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.