使用php插入db时出现mysql错误

时间:2013-12-27 17:07:15

标签: php mysql mysqli

我没有看到任何错误,但它一直告诉我第1行有错误。

这是我的表格:

<section class="loginform tmr">
<form name="login" action="regi.php" method="post" accept-charset="utf-8">
    <label for="username">Username: </label><br />
    <input type="username" name="username" placeholder="Handle" required><br />
    <label for="usermail">Email: </label><br />
    <input type="email" name="usermail" placeholder="yourname@email.com" required><br />
    <label for="password">Password: </label><br />
    <input type="password" name="password" placeholder="password" required><br />
    <input type="submit" value="Login">
</form>
</section>

我的php连接:

$con = mysqli_connect("localhost", "sdfs", "sdfsdfm", "mydb");
//check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql = "INSERT INTO builds (username, email) VALUES ('$_POST[username]','$_POST[email])";

if (!mysqli_query($con,$sql)) {
    die('Error: ' . mysqli_error($con));
}
echo "1 record added";

mysqli_close($con);

我的错误讯息:

  

错误:您的SQL语法出错;检查与MySQL服务器版本对应的手册,以便在第1行“')'附近使用正确的语法

4 个答案:

答案 0 :(得分:3)

你在这一行中缺少一个撇号(注意我已经在{}中包装了变量):

$sql = "INSERT INTO builds (username, email)
        VALUES ('{$_POST[username]}','{$_POST[email]}')";
                                                 //  ^ here...

此外,我建议您在查询中转义任何用户输入或表单数据,以便上述内容成为:

$username = $mysqli->real_escape_string($_POST['username']);
$email    = $mysqli->real_escape_string($_POST['email']);
$sql      = "INSERT INTO builds (username, email) VALUES ('{$username}','{$email}')";

答案 1 :(得分:1)

$username = mysqli_real_escape_string($con, $_POST['username']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$sql = "INSERT INTO builds (username, email) VALUES ('$username ','$email')";

答案 2 :(得分:0)

你需要像字符串一样插入它们

$user=$_POST['username'];
$email=$_POST['email'];

$sql = "INSERT INTO builds (username, email) VALUES ('".$user."','".$email."')";

答案 3 :(得分:0)

那些单引号'在你的sql中不匹配,此外,你可以使用htmlspecialchars()来阻止你注射攻击:

$username = htmlspecialchars($_POST['username']);
$email = htmlspecialchars($_POST['email']);  
$sql = "INSERT INTO builds (username, email) VALUES ('".$username."','".$email."')";