I have created a function that inserts data into MYSQL database dynamically to avoid code repetition just like so :
function insert($table, $data)
{
// connection
global $db;
if(!is_array($data)) die("Error : second parameter must be an array of keys and values");
$keys = array_keys($data);
$values = array_values($data);
// sql query
$sql = "INSERT INTO `$table` (";
// if more than one column
if(count($data) > 1)
{
for($i = 0; $i < count($data) -1; $i++)
{
$sql .= "`$keys[$i]`, ";
}
$sql .= "`" . end($keys) . "`) VALUES (";
for($i = 0; $i < count($data) -1; $i++)
{
$sql .= ":$keys[$i], ";
}
$sql .=":" . end($keys) . ")";
}else{ // only one column
$sql .= "`$keys[0]`) VALUES(:$keys[0])";
}
// make keys as named placeholders
$binds = array_map(function($elem){
return ":".$elem;
}, $keys);
// combine placeholders with values
$binds = array_combine($binds, $values);
$stmt = $db->prepare($sql);
return $stmt->execute($binds) ? true : false;
}
So Later on i can insert data just like that :
echo insert("users",[
"Name" => "Timino",
"Email" => "[email protected]"
]); // result 1 inserted or 0 failed
However its inserting duplicate rows ?? when i debug the code everything looks okay
echo $sql; //INSERT INTO `users` (`Name`, `Email`) VALUES (:Name, :Email)
print_r($binds) // Array
(
[:Name] => Timino
[:Email] => [email protected]
)
What am i doing wrong ?
Note : i have updated the code to procedural to make it easy for everyone who one to test it quickly !
Are you executing this code in your index.php?
echo $db->insert("users",[
"Name" => "Timino",
"Email" => "[email protected]"
]); // result 1 inserted or 0 failed
It might not be a code issue.
I had a similar issue where I was testing the insert in my index.php, and I had a rule in my .htaccess that would redirect not found files to index.php. And when the browser tries to locate your favicon, it's redirected to the index.php which will execute the code once again.
If that's the case, you can try moving your code into another file test.php and call your domain with http://localhost/test.php and check if it's still duplicating.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With