mysql - PHP Dynamic insert function is inserting duplicate rows -


i have created function inserts data mysql database dynamically avoid code repetition :

function insert($table, $data) {     // connection    global $db;      if(!is_array($data)) die("error : second parameter must array of keys , values");      $keys   = array_keys($data);     $values = array_values($data);      // sql query     $sql = "insert `$table` (";     // if more 1 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{ // 1 column          $sql .= "`$keys[0]`) values(:$keys[0])";     }      // make keys named placeholders     $binds = array_map(function($elem){         return ":".$elem;     }, $keys);       // combine placeholders values     $binds = array_combine($binds, $values);       $stmt = $db->prepare($sql);     return $stmt->execute($binds) ? true : false; } 

so later on can insert data :

echo insert("users",[     "name"  => "timino",     "email" => "admin@timino.io" ]); // result 1 inserted or 0 failed 

however inserting duplicate rows ?? when debug code looks okay

echo $sql;  //insert `users` (`name`, `email`) values (:name, :email) print_r($binds) // array (     [:name] => timino     [:email] => admin@timino.io )  

what doing wrong ?

note : have updated code procedural make easy 1 test !

are executing code in index.php?

echo $db->insert("users",[     "name"  => "timino",     "email" => "admin@timino.io" ]); // result 1 inserted or 0 failed 

it might not code issue.

i had similar issue testing insert in index.php, , had rule in .htaccess redirect not found files index.php. , when browser tries locate favicon, it's redirected index.php execute code once again.

if that's case, can try moving code file test.php , call domain http://localhost/test.php , check if it's still duplicating.


Comments

Popular posts from this blog

What is happening when Matlab is starting a "parallel pool"? -

angular - DownloadURL return null in below code -

php - Cannot override Laravel Spark authentication with own implementation -