问题
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
.
回答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
回答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..."
回答3:
"UPDATE test SET page".$pageID."='".$pageProgress."' WHERE userID='".$userID."';"
Dots are in the wrong spot to do it with PHP's string functions.
回答4:
Something like this.
mysql_query("UPDATE test SET page" . $pageID . " = '" . $pageProgress . "' WHERE userID = " . $userID)
回答5:
Try
mysql_query('UPDATE test SET page'.$pageID.'='.$pageProgress.' WHERE userID='.$userID)
回答6:
$updateUserProgress = mysql_query("UPDATE test SET page".$pageID." = '".$pageProgress."' WHERE userID='".$userID."'") or die(mysql_error());
@Marc B ; that's not the question..
回答7:
You don't need to concatenate anything. you do need to sanitize your variable from post though.
if ($_POST['pageProgress']) {
$pageProgress = mysql_real_escape_string($_POST['pageProgress']);
$pageID = 3;
$userID = 1;
$updateUserProgress = mysql_query("UPDATE test SET page$pageID='$pageProgress' WHERE userID='$userID'") or die(mysql_error());
}
来源:https://stackoverflow.com/questions/8232769/php-mysql-how-do-a-concatenate-a-variable-in-a-mysql-query