PHP插入MySQL语法错误 [英] PHP Insert into MySQL syntax error

查看:149
本文介绍了PHP插入MySQL语法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法通过php向MySQL提交一些数据,但出现以下错误:

I'm having trouble submitting some data to MySQL via php, i get the following error:

错误:您的SQL语法有误;请查看与您的MySQL服务器版本相对应的手册,以了解在学生"(UID,名字,姓氏,DOB,紧急联系人,第1行的地址,城市,州"

我不确定我哪里出了问题,任何帮助都很好.

I'm not sure where i've gone wrong, any help would be great.

<?php
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$dob = $_POST['dob'];
$emergencycontact = $_POST['emergencycontactperson'];
$address = $_POST['addressline1'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$homephone = $_POST['homephone'];
$cellphone = $_POST['cellphone'];
$guardian = $_POST['guardian'];
$inneighborhood = 0;
if ($zip == "49503")
    $inneighborhood = 1;

$con = mysqli_connect("localhost", "cookarts_root", "password", "cookarts_database");

// Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql = "INSERT INTO 'student' (FirstName, LastName, DOB, EmergencyContact, Address,       City, State, ZIP, CellPhone, HomePhone, Guardian, InNeighborhood)
VALUES
($firstname', '$lastname', '$dob', '$emergencycontact', '$address', '$city', '$state', '$zip', '$cellphone', '$homephone', '$guardian', '$inneighborhood')";

if ($con->query($sql) === TRUE) {
      echo 'users entry saved successfully';
}   
else {
  echo 'Error: '. $con->error;
}

mysqli_close($con);
?>

如果您需要更多信息,我很乐意提供,再次感谢您的帮助.

If you need more info i'd be happy to provide it, thanks again for the help.

推荐答案

TableNames是标识符,因此不应使用单引号引起来.由于您使用的tableName不是保留关键字,因此您只需删除那些环绕引号,

TableNames are Identifiers so they should not be quoted with single quotes. Since the tableName you've used is not a reserved keyword, you can simply remove those wrapping quotes around,

INSERT INTO student (FirstName, LastName....

当您用单引号引起来时,它将强制该对象成为字符串文字.因此,当标识符用单引号引起来时,这意味着它们不再是标识符.

When you wrap something with single quotes, it forces that object to become a string literal. So when identifiers are wrap with single quotes, it means that they are not identifier anymore.

服务器抛出异常,因为INSERT INTO期望标识符不是字符串文字.

The server throws an exception because INSERT INTO expects an identifier not string literal.

当您不小心使用了 MySQL保留关键字,请勿使用单引号来分隔标识符,而应使用backticks.

When you have accidentally used a table name which is a MySQL Reserved Keyword, don't use single quote to delimit the identifier but with backticks.

作为一个附带说明,如果值( s)是 SQL Injection ,则该查询容易受到攻击)的变量来自外部.请查看下面的文章,以了解如何防止这种情况的发生.通过使用PreparedStatements,您可以摆脱在值周围使用单引号的情况.

As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.

这篇关于PHP插入MySQL语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆