插入数组时PHP | SQL语法错误
我在将数组插入sql数据库时遇到一些问题 我的错误如下:插入数组时PHP | SQL语法错误,php,arrays,insert,implode,Php,Arrays,Insert,Implode,我在将数组插入sql数据库时遇到一些问题 我的错误如下: Unable to add : 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 '06:45:23,i want to leave a comment)' at line 1 我的查询变量为: string(136)
Unable to add : 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 '06:45:23,i want to leave a comment)' at line 1
我的查询变量为:
string(136) "INSERT INTO news_comments (news_id,comment_by,comment_date,comment) VALUES (17263,Philip,2010-05-11 06:45:23,i want to leave a comment)"
我的问题是如何向id添加空值,因为它是主键而不是新闻id
我的插入函数如下所示:
function insertQuery($tbl, &$data)
{
global $mysqli;
$_SESSION['errors'] = array();
require_once '../config/mysqli.php';
$query = "INSERT INTO $tbl (".implode(',',array_keys($data)).") VALUES (".implode(',',array_values($data)).")";
var_dump($query);
if($result = mysqli_query($mysqli, $query))
{
//$id = mysqli_insert_id($mysqli);
print 'Very well done sir!';
}
else
{
array_push($_SESSION['errors'], 'Unable to add : ' . mysqli_error($mysqli));
}
}
$query = "INSERT INTO $tbl (".implode(',',array_keys($data)).") VALUES ('".implode("','",array_values($data))."')";
注意:数组不是我的强项,因此我可能在中正确使用了它们 如果值不是数字,则必须将其置于引号之间。
遍历数组并将值放在引号中,然后可以像在代码段中那样对其进行内爆。您需要使用单引号“yyy-mm-dd hh:mm:ss”包装数据。您需要将它们应用于所有文本字段date、varchar、char、text等。此外,请确保正确转义可能是文本一部分的任何单引号。您需要在我要留下注释的字符串周围加上一个引号 试试这个
$query = "INSERT INTO $tbl (".implode(',',array_keys($data)).") VALUES (\"".implode('","',array_values($data))."\")";
我认为您缺少字符串值周围的引号,例如值应该是:
17263,'Philip','2010-05-11 06:45:23','i want to leave a comment'
注意:不要忘记对字符串值使用mysql\u real\u escape\u string函数。您在这里正确地使用了数组,即使是以奇怪的方式。你的主要问题是,你如何做,你打破了查询:
INSERT INTO news_comments (news_id,comment_by,comment_date,comment) VALUES (17263,Philip,2010-05-11 06:45:23,i want to leave a comment)
应引用字符串值,如下所示:
INSERT INTO news_comments (news_id,comment_by,comment_date,comment) VALUES (17263,'Philip','2010-05-11 06:45:23','i want to leave a comment')
从技术上讲,如果在数字周围加引号,也不会有什么区别,因为MySQL应该根据需要将它们转换为数字。因此,您的代码应该更像这样:
function insertQuery($tbl, &$data)
{
global $mysqli;
$_SESSION['errors'] = array();
require_once '../config/mysqli.php';
$query = "INSERT INTO $tbl (".implode(',',array_keys($data)).") VALUES (".implode(',',array_values($data)).")";
var_dump($query);
if($result = mysqli_query($mysqli, $query))
{
//$id = mysqli_insert_id($mysqli);
print 'Very well done sir!';
}
else
{
array_push($_SESSION['errors'], 'Unable to add : ' . mysqli_error($mysqli));
}
}
$query = "INSERT INTO $tbl (".implode(',',array_keys($data)).") VALUES ('".implode("','",array_values($data))."')";
请注意第二个数组_内爆中的额外引号。这将用一个引号包装每个值,允许在数据库中使用它
但是,请注意,如果任何值包含一个',则它将中断。你需要摆脱这些,通常使用一个双,把它变成。如果你使用它,它将为你解决所有这些问题,但它必须针对每个人的价值进行处理。很好的反馈,伙计们,我现在觉得自己很傻,但我想,当你被某件事情缠住时,很容易错过眼前的事情。