在尝试更新数值时出现语法错误(MySQL)


Getting syntax error when trying to update numerical value (MySQL)

我是一名业余程序员,创建了一个基于PHP的在线门户网站,它将更新与mmo类型游戏相关的MySQL数据库中的值,在该游戏中,我们使用门户网站来跟踪每个用户保护的土地瓷砖总数。

我正在编写脚本,该脚本将通过$_POST数组提交HTML表单,更新给定类型的受保护土地的表计数。

问题中的MySQL表(players)有四个类似的字段(以及其他字段):

  • wild_count
  • city_count
  • nether_count
  • end_count

在HTML表单上,用户可以在提交时选择土地类型,脚本尝试执行字符串连接来完成字段,然后将其提供给准备好的SQL查询中的占位符,如:

//Set land type string
$landtype = $_POST['landtype'] . '_count';
//Process ADD request
if (!isset($_POST['negative']))
{
    $action = 'ADDED'; //This is for a transaction report further down in the code
    try
    {
        $sql = 'UPDATE players SET
            `:landtype` = `:landtype` + :tiles WHERE id = :id';
        $query = $link->prepare($sql);
        $query->bindValue(':landtype', $landtype);
        $query->bindValue(':tiles', $_POST['tiles']);
        $query->bindValue(':id', $_POST['player']);
        $query->execute();
    }
    catch (PDOException $e)
    {
        $error = 'Error updating land count: ' . $e->getMessage();
        include './includes/error.inc.php';
        exit();
    }
...more code follows...

当尝试使用以下代码POST我的表单时,我得到以下错误:

更新土地计数错误:SQLSTATE[42S22]: Column not found: 1054字段列表中未知列" city_count "

(我在表单示例中选择了city)。

我尝试过相同的代码,除了没有围绕占位符:landtype(即$sql = 'UPDATE players SET :landtype = :landtype + :tiles WHERE id = :id';)的反引号,我得到一个不同的错误:

Error updating land count: SQLSTATE[42000]: Syntax Error or access violation: 1064查看与MySQL服务器版本对应的手册,以便在第2行"city_count"="city_count"+"300"WHERE id ="1"附近使用正确的语法

我不确定如何进行。通过创建一个连接字符串来设置字段值的尝试是否会在这里中断它?

不要试图将列名绑定为一个值:

$sql = 'UPDATE players SET `'.$landtype.'` = `'.$landtype.'` + :tiles WHERE id = :id';

PHP PDO语句可以接受表名或列名作为参数吗?