我在以下代码中遇到语法错误,但我找不到它:
$tableSelect = $_POST["tableSelect"];
$companyName = $_POST["companyName"];
$telephone = $_POST["telephone"];
$fax = $_POST["fax"];
$email = $_POST["email"];
$address = $_POST["address"];
$postcode = $_POST["postcode"];
$category = $_POST["category"];
$contact = $_POST["contact"];
$contactTel = $_POST["contactTel"];
$contactEmail = $_POST["contactEmail"];
$sql = "INSERT INTO '" . $tableSelect . "' ('" . $companyName . "', '" . $telephone . "', '"
. $fax . "', '" . $email . "', '" . $address . "','" . $postcode . "', '" . $category . "',
'" . $contact . "', '" . $contactTel . "', '" . $contactEmail . "')";
mysqli_query($con,$sql);
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
干杯!
编辑:我已将代码修改为:
$sql = "INSERT INTO `" . $tableSelect . "` (name, telephone, fax, email, address, postcode, category,
contact, contactTel, contactEmail) VALUES (`" . $companyName . "`, `" . $telephone . "`, `"
. $fax . "`, `" . $email . "`, `" . $address . "`,`" . $postcode . "`, `" . $category . "`,
`" . $contact . "`, `" . $contactTel . "`, `" . $contactEmail . "`)";
现在在“字段列表”中出现错误“错误:未知列[companyName]”,其中[companyName]是通过表单提交的值。但我当然把这个专栏定义为“名字”?
编辑2:谢谢,我现在知道注入问题了。我想让它工作,然后我会把它改成使用预备语句。
答案 0 :(得分:2)
您需要values
声明或select
声明:
"INSERT INTO '" . $tableSelect . "' VALUES ('" . $companyName . "', '" . $telephone . "', '"
. $fax . "', '" . $email . "', '" . $address . "','" . $postcode . "', '" . $category . "',
'" . $contact . "', '" . $contactTel . "', '" . $contactEmail . "')";
但是,我还建议您在insert
语句中包含列名:
"INSERT INTO '" . $tableSelect ."(companyname, telephone, fax, email, address, postcode, category, contact, contactTel, contactEmail) ".
"' VALUES ('" . $companyName . "', '" . $telephone . "', '"
. $fax . "', '" . $email . "', '" . $address . "','" . $postcode . "', '" . $category . "',
'" . $contact . "', '" . $contactTel . "', '" . $contactEmail . "')";
我不确定这些名字是否正确。
答案 1 :(得分:1)
引用表名时使用反引号:`而不是直引号:
而不是:
'" . $companyName . "'
这样:
`" . $companyName . "`
使用预准备语句而不是直接将变量放入查询中。并检查表名是否正确,因为现在您可以使用SQL注入。
答案 2 :(得分:1)
请检查插入查询语法
您的计划中缺少值:
按照以下语法:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
答案 3 :(得分:1)
忽略注射问题......
$sql = "
INSERT INTO $tableSelect
(name
,telephone
,fax
,email
,address
,postcode
,category
,contact
,contactTel
,contactEmail
) VALUES
('$companyName'
,'$telephone'
,'$fax'
,'$email'
,'$address'
,'$postcode'
,'$category'
,'$contact'
,'$contactTel'
,'$contactEmail'
);
";
顺便说一句,在我的(有限)经验中,调用变量(例如'$ companyName')和列(例如name
)两个(稍微)不同的东西的做法会变得非常混乱。
答案 4 :(得分:0)
尝试像这样的查询
$query="insert into abc (a,b,c) values ('a','b','c')
and first check your all variables using isset()
答案 5 :(得分:0)
请尝试以下查询:
$sql = "INSERT INTO $tableSelect ('" . $companyName."', '".$telephone."',
'".$fax."', '".$email."', '".$address."', '".$postcode."', '".$category."',
'".$contact."', '".$contactTel."', '".$contactEmail."')";
如果仍然出错,那么你应该使用mysql_real_escape_string()函数 数据可能包含特殊字符。