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 !
$db->insert(..)call with a simple$db->exec("INSERT ...")and look if it still inserts twice. If so - theinsertmethod has nothing to do with your problem.