Monday 10 June 2019

sql - Executing MySQL Query from PHP error



This part of my code creates a multiple query by this:



$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());


However, I get an error:




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 'INSERT INTO assignments (user_id, project_id, assigned_date) ' at line 3




However, if I echo $sql it turns out something like this:



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');


THEN I manually execute the SQL into PhpMyAdmin, it works fine, but how come it doesn't work when PHP executes it and outputs an error?


Answer



mysql_query can only execute one query at a time



Try this:



$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());
}

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...