1

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.

Joe Cool
  • 62
  • 7
  • 1
    Make `$finished_size` a parameter to the function. – Barmar Oct 22 '15 at 20:28
  • Stop what you're doing: http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php – miken32 Oct 23 '15 at 18:16
  • @miken32 Yes, you're right, but I have to use that awful and deprecated method because this is very old software and I've been instructed to do so! – Joe Cool Oct 27 '15 at 16:50

3 Answers3

2

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);
Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

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";
Martin Heralecký
  • 5,649
  • 3
  • 27
  • 65
0

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.

Joe Cool
  • 62
  • 7