Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP/mySQL: How do a concatenate a variable in a mysql query? [duplicate]

What is the proper way to concatenate text and a variable in PHP inside a mysql_query? Here is my attempt:

page.'$pageID'

I want it to output page3.

Here is all of the code (simplified to focus on the mysql_query):

if ($_POST['pageProgress']) {
        $pageProgress = $_POST['pageProgress'];
        $pageID = 3;
        $userID = 1;
        $updateUserProgress = mysql_query("UPDATE test SET page.'$pageID'='$pageProgress' WHERE userID='$userID'") or die(mysql_error());
    }

All of the code works perfectly if I simply replace page.'$pageID' with page3.

like image 717
Mark Rummel Avatar asked Dec 29 '25 15:12

Mark Rummel


2 Answers

You do not need the .. PHP parses double quoted (") strings and replaces the variables with their values. As such:

$pageID = 3;
echo "UPDATE test SET page$pageID = '$pageProgress' WHERE userID = '$userID'";

http://codepad.viper-7.com/uIdqqH

like image 185
Alex Turpin Avatar answered Dec 31 '25 05:12

Alex Turpin


The problem is that your .'$pageID' is inside the double-quoted string; you don't concatenate this on the MySQL side; it gets parsed long before MySQL ever sees it.

It might be that you were trying to escape the field name for Mysql, in that case, you use backticks.

Try:

'UPDATE test SET `page'.$pageID.'`=\''.$pageProgress.'\' WHERE...'

Or, much easier on the eyes:

"UPDATE test SET `page{$pageID}`='{$pageProgress}' WHERE..."
like image 36
Kato Avatar answered Dec 31 '25 07:12

Kato



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!