Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP/MySQLi - Fatal error: Call to a member function mysqli_query() on a non-object

Tags:

php

mysqli

Here is my code:

require "../include/functions.php";

error_reporting(E_ALL);
ini_set('display_errors', '1'); 

ConnectWithMySQLiDatabase();

$Cat = addslashes($_POST["Category"]);

$v = $conn->mysqli_query($conn,"SELECT * FROM `categories` WHERE `id`=$Cat");
$vrowi = mysqli_fetch_array($v, MYSQLI_ASSOC);

$url = $conn->real_escape_string($vrowi['Link']);

Here is what i have in functions.php:

function ConnectWithMySQLiDatabase() {

     global $dbhost, $dbuser, $dbpass, $database, $HTTP_SERVER_VARS;

    $conn = new mysqli($dbhost, $dbuser, $dbpass, $database);
    // Check connection
    if (mysqli_connect_errno())
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }


    $conn->set_charset("utf8");

    global $conn;

}

The variables $dbhost, $dbuser, $dbpass, $database, are set correctly.

When i try to execute this mysqli_query i receive the following error:

<b>Fatal error</b>:  Call to a member function mysqli_query() on a non-object in <b>/fetch_category_products.php</b> on line <b>19</b><br />

Line 19 is:

$v = $conn->mysqli_query($conn,"SELECT * FROM `categories` WHERE `id`=$Cat");

Can you please tell me where is my mistake and how can i fix it ?

Thanks in advance!

like image 381
Venelin Avatar asked Oct 19 '22 19:10

Venelin


1 Answers

That error arises because the database connection isn't working – it literally means that the value of $conn isn't an object, which probably means it's either not set or set to false because the connection failed. Change ConnectWithMySQLiDatabase() so that its last line is not global $conn; but return $conn;.

Now change the way you call that function from ConnectWithMySQLiDatabase(); to be $conn = ConnectWithMySQLiDatabase(); and I believe the problem will go away.

OP posted an update after this change, and the confusion became more clear: now they have a MySQLi connection, they should just use query, like this:

$v = $conn->query("SELECT * FROM `categories` WHERE `id`=$Cat");
like image 180
TwoStraws Avatar answered Oct 21 '22 17:10

TwoStraws