I'm having trouble with a specific SQL transaction, which runs fine when I run it in phpMyAdmin, but refuses to run from my own php script.
<?php
//connect
$link = mysqli_connect('localhost', 'root', '', 'chemDB');
if (!$link) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
mysqli_select_db($link, 'chemDB');
echo "Connected successfully\n";
//open import CSV
$file = fopen('cas_list.csv', 'r');
//convert decimal comma to float
function commaToPoint($val)
{
$val = str_replace(',', '.', $val);
return floatval($val);
}
//cycle through csv lines
while (! feof($file))
{
$data = fgetcsv($file, '', ';');
$un = strval($data[0]);
$cas = strval($data[1]);
$name = strval($data[2]);
$m_mass = commaToPoint($data[3]);
$m_n = commaToPoint($data[4]);
$m_s = commaToPoint($data[5]);
$m_cl = commaToPoint($data[6]);
$m_f = commaToPoint($data[7]);
$m_br = commaToPoint($data[8]);
$m_other= commaToPoint($data[9]);
$query = "BEGIN;
INSERT INTO chemical (cas, name) VALUES ('$cas', '$name');
SELECT LAST_INSERT_ID() INTO @chemical_id;
--followed by more SQL...
COMMIT;";
print_r($query);
$result = mysqli_query($link, $query);
if (!$result)
{
echo("\nError description: " . mysqli_error($link)."\n\n");
}
}
fclose($file);
mysqli_close($link);
?>
In this case, the table `chemical` in question has 3 fields: id(int 11), cas(varchar24) and name(varchar255).
One of the input lines from the CSV is:
0072;121-82-4;Cyclotrimethyleentrinitramine, bevochtigd;222,3;6;;;;;138,24;
print_r($query)
prints out the resulting query string which works fine in phpMyAdmin, but not with mysqli_query()
:
BEGIN;
INSERT INTO `chemical` (`cas`, `name`) VALUES ('121-82-4', 'Cyclotrimethyleentrinitramine, bevochtigd');
SELECT LAST_INSERT_ID() INTO @chemical_id;
--followed by more SQL...
COMMIT;
However, no matter what format I use I end up with the error:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'BEGIN; INSERT INTO `chemical` (`cas`, `name`) VALUES ('121-82-4', 'Cyclotrimet' at line 2`