3

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 !

14
  • did you dump the sql string before execute it ? Commented Aug 18, 2017 at 15:05
  • 1
    kinda weird, i assume that echo $db->inset isn't in loop or called 2 times ? Actually i find nothing wrong in your code Commented Aug 18, 2017 at 15:12
  • 1
    Can you add the code calling this insert? Commented Aug 18, 2017 at 15:32
  • 1
    Yes, the code wrapping the db->insert: Something must be calling it twice since your code looks OK (nice safe against SQL injection) Commented Aug 18, 2017 at 15:39
  • 1
    Replace your $db->insert(..) call with a simple $db->exec("INSERT ...") and look if it still inserts twice. If so - the insert method has nothing to do with your problem. Commented Aug 18, 2017 at 15:57

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

you were absolutely right !! what happened to me is i had the same problem on both apache and nginx so that's what makes me think that it is a code problem and not a server problem but after commenting redirection rules every think works as prefered here is what was causing the problem for apache RewriteRule ^(.*)$ index.php?uri=$1 [QSA,L] and for nginx try_files /$uri /$uri /index.php?uri=$uri;
@Timino Glad you have it figured out :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.