2016-11-03 74 views
0

我是一名业余程序员,他创建一个基于PHP的在线门户,它将更新MySQL数据库中与MMO类型游戏相关的值,其中我们使用门户跟踪每个用户所保护的地块的总数。尝试更新数值时出现语法错误(MySQL)

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

有问题的MySQL表(players)有四个类似领域(以及其他领域):

  • wild_count
  • city_count
  • nether_count
  • END_COUNT

在HTML表单时,用户可以在提交时选择一种土地类型,并且脚本尝试执行一个str荷兰国际集团串连完成字段,然后将其提供在准备的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... 

当尝试使用下面的代码后我的形式,我得到以下错误:

Error updating land count: SQLSTATE[42S22]: Column not found: 1054 Unknown column ''city_count'' in 'field list'

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

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

Error updating land count: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''city_count' = 'city_count' + '300' WHERE id = '1'' at line 2

我不能确定如何进行。通过创建连接字符串来设置字段值的尝试是否在此打破它?

+0

你放在错误的地方$ SQL =“更新球员反引号SET ':landtype' =:landtype + :tiles WHERE id =:id';在附近去除反引号lantype = – JYoThI

+0

感谢您的建议,我为在帖子中未更清晰表示歉意,但我已经尝试了在占位符周围使用和不使用反引号,并且出现了不同的错误(最后两段)。任何其他想法? – ajd2598

+0

试试这个$ sql ='UPDATE players SET' landtype' =:landtype +:tiles WHERE id =:id'; – JYoThI

回答

0

不要试图绑定列名就像是一个值:

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

Can PHP PDO Statements accept the table or column name as parameter?

+0

这解决了我的问题。谢谢。我可以问一下,为什么使用反引号,紧接着是单引号和反引号,最后围绕这两个字符串? – ajd2598

+0

backtick是告诉mysql它是一个列名的方法(以防有人用保留关键字命名列)。你的字符串($ sql)是单引号的,所以我在反引号后结束了字符串,然后我用点(。)连接器继续使用该变量的字符串,然后等。 – WEBjuju

+0

完美感,再次感谢。我试图评价你的答案,但显然我还没有足够的声望。尽管你有我的感谢。 – ajd2598

相关问题