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.

3
  • 1
    Make $finished_size a parameter to the function. Commented Oct 22, 2015 at 20:28
  • Stop what you're doing: stackoverflow.com/questions/12859942/… Commented Oct 23, 2015 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! Commented Oct 27, 2015 at 16:50

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

Comments

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";

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.