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

36,453

Solution 1

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

Solution 2

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

Solution 3

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

Dots are in the wrong spot to do it with PHP's string functions.

Solution 4

Something like this.

mysql_query("UPDATE test SET page" . $pageID . " = '" . $pageProgress . "' WHERE userID = " . $userID)
Share:
36,453
Mark Rummel
Author by

Mark Rummel

I'm a modern web designer. I have enjoyed designing and building websites for my clients for over 10 years. I have extensive experience in many web technologies, including HTML5, CSS3, javascript, jQuery, LESS, PHP, MySQL, Wordpress, MailChimp, PayPal, Stripe, and more.

Updated on July 15, 2022

Comments

  • Mark Rummel
    Mark Rummel almost 2 years

    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.