Q:

PHP inserts data right all the time but once failed and inserted duplicate?

I have this PHP code that should check site stats and is registering all the visits. All works nicely but I found out by accident that there was one double insertion and am speechless, with the same IP and date.
    $ip = $_SERVER['REMOTE_ADDR'];
    $date = date("Y-m-d");
    $time = time();

    $stmt = mysqli_prepare($dbconnect, "SELECT id FROM traffic WHERE ip=? && date=? LIMIT 1");
    mysqli_stmt_bind_param($stmt, 'ss', $ip, $date);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_store_result($stmt);
    $res=mysqli_stmt_num_rows($stmt); 
    if ($res == 0) {
     $inser = mysqli_prepare($dbconnect, "INSERT INTO traffic (ip,date,time) VALUES (?, ?, ?)");
    mysqli_stmt_bind_param($insert, 'ssi', $ip, $date, $time);
      mysqli_stmt_execute($insert);
      mysqli_stmt_close($insert);   
    }else {
    mysqli_stmt_bind_result($stmt, $id);
    mysqli_stmt_fetch($stmt);
    $update = mysqli_prepare($dbconnect, "UPDATE traffic SET pages=pages+1, time=? WHERE id=? LIMIT 1");
    mysqli_stmt_bind_param($update, 'ii', $id, $time);
    mysqli_stmt_execute($update);
    mysqli_stmt_close($update); 
    }
    mysqli_stmt_close($stmt);

made more accurate

A:

Your code could be called twice in short succession, and run the 1st select, get 0 results, and insert a record. The 2nd select runs in parallel just before the 1st record is inserted, so also gets 0 results, so it runs the insert - you now have 2 records with same data.

