我的代码的这部分创建了一个多重查询:
$sql = "";
$sql .= "INSERT INTO projects
(project_id, project_name, project_description, project_deadline, project_status, project_priority)
VALUES ('" . $project_id . "', '" . $name . "', '" . $description . "', '" . $final_deadline . "', '" . $status . "', '" . $priority . "');";
foreach($assignments as $assigned_user)
{
$sql .= "INSERT INTO assignments
(user_id, project_id, assigned_date)
VALUES ('" . $assigned_user . "', '" . $project_id . "', '" . time() . "');";
}
$result = mysql_query($sql) or die(mysql_error());
然而,我收到错误:
您的SQL语法有错误;查看与MySQL服务器版本对应的手册,以便在第3行的“INSERT INTO assignments(user_id,project_id,assigned_date)”附近使用正确的语法
然而,如果我回复$sql
,结果是这样的:
INSERT INTO projects (project_id, project_name, project_description, project_deadline, project_status, project_priority) VALUES ('7090', 'Sup :D', 'OMG!', '716770800', '1', '1');
INSERT INTO assignments (user_id, project_id, assigned_date) VALUES ('12', '7090', '1284139311');
INSERT INTO assignments (user_id, project_id, assigned_date) VALUES ('11', '7090', '1284139311');
然后我手动执行SQL到PhpMyAdmin,它运行正常,但是当PHP执行它并输出错误时它怎么会不起作用?
答案 0 :(得分:1)
mysql_query
一次只能执行一个查询
试试这个:
$sql = "INSERT INTO projects
(project_id, project_name, project_description, project_deadline, project_status, project_priority)
VALUES ('" . $project_id . "', '" . $name . "', '" . $description . "', '" . $final_deadline . "', '" . $status . "', '" . $priority . "');";
$result = mysql_query($sql) or die(mysql_error());
foreach($assignments as $assigned_user)
{
$sql = "INSERT INTO assignments
(user_id, project_id, assigned_date)
VALUES ('" . $assigned_user . "', '" . $project_id . "', '" . time() . "');";
$result = mysql_query($sql) or die(mysql_error());
}
答案 1 :(得分:1)
mysql_query函数不支持多个查询。检查mysqli :: multi_query
答案 2 :(得分:1)
学习SQL兄弟,它规则;)
$sql = "INSERT INTO assignments
(user_id, project_id, assigned_date) ";
foreach($assignments as $assigned_user)
{
$sql.= " VALUES ('" . $assigned_user . "', '" . $project_id . "', '" . time() . "') ";
}
我希望你的所有变量都被转义。
答案 3 :(得分:0)
我的猜测是mysql_query函数不允许执行多个语句,每个语句都需要单独执行。
从更大的角度来看,请考虑以下帖子:Overwriting data in a MySQL table。总之,通过在执行时连接字符串来构建查询是一种灾难,您将容易受到SQL注入攻击和其他错误的攻击。考虑使用PDO抽象层而不是调用mysql特定函数,并研究使用参数化查询而不是像你一样构建字符串。
这是初学者犯的一个标准错误(没有得到网上大量例子以及提供不良指导的书籍的帮助)所以如果你是初学者,请不要为此感到难过,请记住你不应该使用这种方法在生产系统中。