SQL语法错误,连接问题简单形式PHP

时间:2012-02-20 19:41:05

标签: php mysql sql data-connections

我有一个简单的表单,可以在我的服务器上的表中插入数据。我已经设置了一个特殊用户来处理这个问题,只有插入权限。我收到连接和语法错误。

这是我的表格:

<form id="form1" name="form1" method="post" action="mailform.php" onsubmit="return validateForm();">

    <input type="text" id="First" maxlength="100" autocorrect placeholder="First name" />
    <input type="text" id="Last" maxlength="100" autocorrect placeholder="Last name" />
    <input type="text" id="Email" maxlength="100" autocorrect placeholder="Email address" />
    <select name="SalesPerson">
        <option value="SP1">SP1</option>
        <option value="SP2">SP2</option>
        <option value="SP3">SP3</option>
        </select>
    <select name="Show">
        <option value="Show1">Show1</option>
        <option value="Show2">Show2</option>
        </select>

        <button type="submit" id="submit" class="oneup">Submit</button>

</form>

以及在mailform.php,我们有:

<?php

    $name = "xxx_xxx";
    $name = mysql_real_escape_string($name);
    $SQL = "SELECT * FROM users WHERE username = '$name'";

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

mysql_select_db("xxx_x", $con);

$sql="INSERT INTO email_signup (First, Last, Email, SalesPerson, Show)
VALUES
('$_POST[First]','$_POST[Last]','$_POST[Email]','$_POST[SalesPerson]','$_POST[Show]')";

if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }

mysql_close($con)
?>

这是错误 -

Warning: mysql_real_escape_string() [<a href='function.mysql-real-escape-string'>function.mysql-real-escape-string</a>]: Access denied for user 'xxx'@'localhost' (using password: NO) in <b>.../mailform.php</b> on line 28

Warning: mysql_real_escape_string() [<a href='function.mysql-real-escape-string'>function.mysql-real-escape-string</a>]: A link to the server could not be established in <b>.../mailform.php</b> on line 28 Error: 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 'Show) VALUES ('','','','SP1','Show1')' at line 1

知道我为什么会遇到连接问题?我在另一个地方设置了一个几乎相同的表格,工作正常。

3 个答案:

答案 0 :(得分:2)

首先建立连接,然后运行mysql_real_escape_string(),然后运行查询。 mysql_real_escape_string()实际上连接到数据库以让它转义你的字符串。如果你没有连接它就不会工作

答案 1 :(得分:1)

首先尝试连接。

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


 $name = "xxx_xxx";
    $name = mysql_real_escape_string($name);
    $SQL = "SELECT * FROM users WHERE username = '$name'";

答案 2 :(得分:0)

注意:此答案不会尝试解决主要的SQL注入漏洞。有关更深入的讨论,请阅读问题下方的评论。

Show 是保留字

使用

$sql="INSERT INTO email_signup (`First`, `Last`, `Email`, `SalesPerson`, `Show`)
VALUES
('$_POST[First]','$_POST[Last]','$_POST[Email]','$_POST[SalesPerson]','$_POST[Show]')";