Reputation: 129
I'm compiling a query in PHP to insert products in the db:
$query = "";
if ($A > 0) {$query .="INSERT INTO ped_prod (`ped_id`, `prod_id`, `cant`) VALUES ($last_id, 1, $A); ";}
if ($B > 0) {$query .="INSERT INTO ped_prod (`ped_id`, `prod_id`, `cant`) VALUES ($last_id, 2, $B); ";}
if ($C > 0) {$query .="INSERT INTO ped_prod (`ped_id`, `prod_id`, `cant`) VALUES ($last_id, 3, $C); ";}
While running the query through mysql_query($prodquery, $conexion)
I'm getting the following 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 ped_prod (`ped_id`, `prod_id`, `cant`) VALUES (13, 3, 2)' at line 1
I have tried:
- Exchanging quotes ('), double quotes (") and backticks (`)
- Checking the list of MySQL reserved words
- Running the query in PHPmyAdmin (it says '#1 affected line' but it loads the data to the table, which is not the case when executing the script in the browser)
What am I missing? Thanks in advance!
Upvotes: 0
Views: 79
Reputation: 74046
mysql_query()
supports just one query at a time. See the respective PHP docs:
mysql_query() sends a unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified link_identifier.
So in your case, just run each INSERT
statement seperatly and you should be fine.
Another option, as all your inserts are similar, would be to connect those by concatenation of the value clauses:
$values = array();
if ($A > 0) {$values[] ="($last_id, 1, $A)";}
if ($B > 0) {$values[] ="($last_id, 2, $B)";}
if ($C > 0) {$values[] ="($last_id, 3, $C)";}
// echo query if needed
if ( count( $values ) > 0 ) {
$queries = 'INSERT INTO ped_prod (`ped_id`, `prod_id`, `cant`) VALUES ' . implode( ',', $values );
// execute query
// ...
}
Besides, mysql_X
functions are deprecated. Switch to PDO or mysqli.
Upvotes: 1