I have read many similar questions mentioning this same error but wasn't able to apply the solutions mentioned to my case. I use a prepared statement to insert data in my database (MariaDB) using PHP and PDO. Most of the times it works, but at times it gives the following error:
PHP message: PHP Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 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 'test <snip>
The error comes up when a special character (such as a single quote) is used in the data entered.
Here is the function used to enter the data in the DB:
function insert($table,$data){
global $conn;
ksort ($data);
$fieldNames = '`'.implode('`, `', array_keys($data)).'`';
$fieldvalues = "'".implode("','", array_values($data))."'";
$sql = 'INSERT INTO '.$table.' ('.$fieldNames.') VALUES('.$fieldvalues.')';
$statement = $this->conn->prepare($sql);
$statement->execute();
return 'true';
}
And here is an example of how the insert function is called:
if (isset($_POST['name'])) {
$data = array(
'name'=>"any name",
'nickname'=>"any nickname",
'address'=>"any address",
);
insert('table_name',$data);
}
Any help on solving this issue would be appreciated.
edit: Here is is partial db/tabledump as per requested (edited for clarity):
-- MySQL dump 10.19 Distrib 10.3.29-MariaDB, for debian-linux-gnu (x86_64)
--
-- Host: localhost Database: database_name
-- ------------------------------------------------------
-- Server version 10.3.29-MariaDB-0+deb10u1
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `sampletable`
--
DROP TABLE IF EXISTS `sampletable`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `sampletable` (
`row_id` int(11) NOT NULL AUTO_INCREMENT,
`data_id` varchar(25) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`data_date` timestamp NOT NULL DEFAULT current_timestamp(),
`data_address` varchar(120) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`data_name` varchar(120) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`row_id`)
) ENGINE=InnoDB AUTO_INCREMENT=01 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;