I have error in this when I upload the data from .csv file from other php file, and my error is :-
"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 "
function array_to_sql($queryData , $table , $multiple = true){
// Create connection
$conn = new mysqli("localhost","root", "", "mydata");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//If multiple data
else
{
foreach($queryData as $queryEntry)
{
if (count($queryEntry) > 0) {
foreach ($queryEntry as $key => $value) {
$value = "'$value'";
$updates[] = "$key = $value";
}
}
$implodeArray = implode(', ', $updates);
//print_r($updates);
$sql = "INSERT INTO `$table` (`".implode("` , `",array_keys($queryEntry))."`) VALUES('".implode("' , '",array_values($queryEntry))."') ON DUPLICATE KEY UPDATE $implodeArray";
if ($conn->query($sql) === TRUE) {
echo "Request Updated";
} else {
echo "Error: ". "
" . $conn->error . $sql;
}
}
}
}
?>
Answer
Your CSV fields contain spaces, which is not allowed for MySQL field names.
You need to manipulate $key or put it in quotes as is
if (count($queryEntry) > 0) {
foreach ($queryEntry as $key => $value) {
$key='`'.$key.'`';
$value = "'$value'";
$updates[] = "$key = $value";
}
}
No comments:
Post a Comment