Reputation: 62
I am having a problem with passing a $query variable to a mysql_query command. So if I do this I get an update in the database (which I wanted):
$query = "UPDATE master SET finished_size = '$finished_size' WHERE id = $id";
mysql_query ($query, $db);
However, I need to use a function to do this. I'm trying to use this code, but I am no longer able to get the update to the database that I wanted:
if ( !function_exists("testQuery") ) {
function testQuery($id) {
return 'UPDATE master SET finished_size = "$finished_size" WHERE id = $id';
}
}
$query = testQuery($id);
mysql_query ($query, $db);
I have tried many ways of doing this, but the $query variable which contains the string to pass to the mysql_query function doesn't seem to be recognized. But I don't know how else to do this the proper way.
Also, I realize mysql_query is an old function, but this is the code that I have to use because I'm working on very old software.
Upvotes: 1
Views: 186
Reputation: 62
It turned out that the problem was that I was using $_POST variables, that had already been extracted, so that $finished_size was no longer treated as a global variable (like $_POST['finished_size'] would be). And so the extracted variable did not have scope access within the function.
So I just re-extracted $_POST inside the function. I had many $_POST variables coming in from a form, and so extracting them inside the function seems to be a fairly convenient way to pass them back to $query.
The answers that were given prior to this were helpful for me to realize that it was a scope issue.
Upvotes: 0
Reputation: 5779
If you're putting a variable to a string without connecting more strings, you have to use quotes, not apostrophes. So:
return "UPDATE master SET finished_size = '$finished_size' WHERE id = $id";
Upvotes: 1
Reputation: 780798
Add another parameter to the function.
Also, variables are only expanded inside double quotes, not single quotes. See What is the difference between single-quoted and double-quoted strings in PHP?
if ( !function_exists("testQuery") ) {
function testQuery($id, $finished_size) {
return "UPDATE master SET finished_size = '$finished_size' WHERE id = $id";
}
}
$query = testQuery($id, $finished_size);
mysql_query ($query, $db);
Upvotes: 2