PHP / MySQLi - Fatal error: calling mysqli_query () member function for an object without an object

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, set correctly.

When I try to execute this mysqli_query, I get 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:

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

Could you tell me where is my mistake, and how can I fix it?

Thanks in advance!

+5
source share
1 answer

This error occurs because the connection to the database does not work - this literally means that the value of $conn not an object, which probably means that it is either not installed or set to false because the connection failed . Modify ConnectWithMySQLiDatabase() so that its last row is not global $conn; , and return $conn; .

Now change the way you call this function from ConnectWithMySQLiDatabase(); like $conn = ConnectWithMySQLiDatabase(); , and I believe that the problem will disappear.

The OP published an update after this change, and the confusion became clearer: now they have a MySQLi connection, they should just use query , for example:

 $v = $conn->query("SELECT * FROM `categories` WHERE `id`=$Cat"); 
+3
source

Source: https://habr.com/ru/post/1238763/


All Articles