我在表单中添加撇号时出现MySQL错误

时间:2013-09-15 12:59:31

标签: php html mysql database

我正在尝试将一个撇号添加到一个表单中,然后保存到数据库中,但是当添加撇号时表单将不会保存。

这是我的代码:

           <?php

$abouttitle=$_POST[abouttitle];
$aboutcontent=$_POST[aboutcontent];
$aboutside=$_POST[aboutside];
$aboutsidetitle=$_POST[aboutsidetitle];  

  $con= mysql_connect("localhost","XXX","XXX");
  if (!$con) 
  {
   die('Could not connect: ' . mysql_error());
   }

   mysql_select_db("cl49-XXX", $con);
$result =   

$aboutcontent = mysql_real_escape_string($aboutcontent);
$abouttitle = mysql_real_escape_string($abouttitle);
$aboutside = mysql_real_escape_string($aboutside);
$aboutsidetitle = mysql_real_escape_string($aboutsidetitle); 

$query = "
UPDATE ADMIN
SET aboutcontent='$aboutcontent',
    abouttitle='$abouttitle',
    aboutside='$aboutside',
    aboutsidetitle='$aboutsidetitle'
");
$result = mysql_query($query);

当我在表单中添加撇号以将其保存到数据库时,我得到以下错误

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use

2 个答案:

答案 0 :(得分:1)

你需要从php端转义你的values使用像

这样的函数

mysqli_real_escape_string如果您使用mysqli扩展程序或

如果您使用mysql_real_escape_string扩展程序

,请

mysql

答案 1 :(得分:1)

是。在执行查询之前使用mysql_real_escape_string

$aboutcontent = mysql_real_escape_string($aboutcontent);
$abouttitle = mysql_real_escape_string($abouttitle);
$aboutside = mysql_real_escape_string($aboutside);
$aboutsidetitle = mysql_real_escape_string($aboutsidetitle); 

一旦您转义了变量,就可以执行查询:

$query = "
UPDATE ADMIN
SET aboutcontent='$aboutcontent',
    abouttitle='$abouttitle',
    aboutside='$aboutside',
    aboutsidetitle='$aboutsidetitle'
";
$result = mysql_query($query);

旁注: Please, don't use mysql_* functions in new code。它们不再被维护and are officially deprecated。转而了解prepared statements,并使用PDOMySQLi - this article将帮助您确定哪个。如果您选择PDO here is a good tutorial