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

我只是一个虾纸丫 提交于 2020-01-13 18:07:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!