00 Votes

PHP: MySQL request within a function

Question by Chematik | 2012-04-24 at 20:25

I want to run a MySQL query within a function in PHP. My code looks something like this, all things, that are not important, I have dropped:

function CheckID($id) {
   $query = "... WHERE id = $id";
   mysql_db_query($db, $query, $con);
}
 
//...
 
// Calling the function causes the error:
CheckID($id); 
 
// The same code from the function at the same place
// works fine:
$query = "... WHERE id = $id";
mysql_db_query($db, $query, $verb);

Now this leads permanently to this error message:

Warning: mysql_db_query() expects parameter 3 to be resource, 
null given in XXX.php on line 16
Warning: mysql_fetch_row() expects parameter 1 to be resource, 
null given in XXX.php on line 17

I have no idea where the bug is. Because, when I place instead of the call of the function, the code of the function at the same place, everything works fine!

ReplyPositiveNegative
1Best Answer1 Vote

I suppose, it is because of your variables $db and $con, which you probably integrate with an include() outside of the function. The result, however, is, that the two variables are not defined within the function, and so it comes to the error messages that the parameters are not defined.

Try it this way, by passing the parameters to the function, which make the parameter also available inside the function:

function CheckID($id, $db, $con) { /*...*/ }
 
// Call:
CheckID($id, $db, $con);

Alternatively, you could also define or include the variables within the function in order to make them available.
2012-04-27 at 13:39

ReplyPositive Negative
Reply

Related Topics

PHP: Current Date and Time

Tutorial | 0 Comments

PHP: Sending an E-Mail

Tutorial | 0 Comments

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.