Jump to content

Warning: Mysqli_Query() Expects Parameter 1 To Be Mysqli, Null Given


chiefboz

Recommended Posts

Hello —

 

This is probably one of the most common mysqli errors out there, but it has appeared on my webpage. The problem is on line 10. This file is used as a global functions file - so I can essentially use db_query(INSERT INTO...) in a different page and have the function run.

 

For security reasons I have removed the actual usernames and such from the code, and it is pasted below. Any help would be greatly appreciated.

 

<?php
// Function to connect to the database.
function db_connect() {
$dbc = mysqli_connect('host','user','********','db');
}

// Function to run database queries.
function db_query($q) {
global $dbc;
$dbq = mysqli_query($dbc, $q); // ERROR OCCURS HERE
if(!$dbq) {
return false;
} else {
$r = mysqli_store_result($link);
}
}
?>

Link to comment
Share on other sites

The function parameter $q gives it a query. For example, in another file register.php, I have

 

db_query("INSERT INTO user_accounts (firstname, lastname, email, username, reg_timestamp, verification_code, vcode_expire) VALUES ('$fn', '$ln', '$e1', '$un', $time, $v, $vcexp)");

 

where $fn, $ln, $e1 and $un are filled in by the user on a form. $time, $v and $vcexp are generated automatically.

 

The code above is just a function for use in other files.

Link to comment
Share on other sites

The 1st parameter is the mysqli link.

 

The original error is because $dbc is not a global variable and doesn't exist outside of the db_connect(){} function. To get your existing code to 'work', you would need to return the connection resource from the db_connection() function and assign it to a $dbc variable in the main program's scope.

Edited by PFMaBiSmAd
Link to comment
Share on other sites

^^^ if by that you mean you are calling mysqli_connect() right before the mysqli_query() statement, don't. Creating a database connection is a fairly long process. You should not be making a database connection before each query. You should make ONE database connection and use it for the duration of the code on any one page.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.