简体   繁体   中英

PHP/MySQLi - Fatal error: Call to a member function mysqli_query() on a non-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, 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!

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM