"Call to a member function mysql_query() on a non-object" when performing a query inside a function
I have a function
<?php
function drop() {
$query = "SELECT revenueCodeID, code FROM revenuecodetable";
$result = $dbx->mysql_query($query);
echo '<select>';
echo '<option value="">Revenue Code</option>';
while ($row = mysql_fetch_array($result)) {
echo '<option value="'.$row['revenueCodeID'].'">'.$row['code'].'</option>';
}
echo '</select>';
}
?>
And 开发者_StackOverflow中文版I have a page that calls the function
<!DOCTYPE html>
<?php
require 'headerInfo.php';
require 'revenueCodeDropdown.php';
?>
<html>
<body>
<?php drop(); ?>
</body>
</html>
headerInfo.php allows for calling the database using $dbx.
When I try and call the function, I get
Fatal error: Call to a member function mysql_query() on a non-object in /var/www/legacy_nas/nas/revenueCodeDropdown.php on line 4
If I take the function syntax out it works fine. Any ideas to help fix this?
Declare $dbx
as global
function drop() {
global $dbx;
.....//rest of stuff
}
OR
Pass object as function parameter
function drop($dbx) {
and call statement
<?php drop($dbx); ?>
You should understand the variable scope. Outer Variables are not available inside the function by default. They can be declared as global or can be passed as an argument.
Did you instantiate the $dbx
object ?
精彩评论