I'm reading data from a .txt file to a MySql db, and adding a unique token.
Like this:
$host = 'localhost';
$db = 'people';
$user = 'xxx';
$pass = 'xxx';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
$open = fopen('data.txt','r');
while (!feof($open))
{
$getTextLine = fgets($open);
$explodeLine = explode("\t",$getTextLine);
$token = openssl_random_pseudo_bytes(16);
$token = bin2hex($token);
list($name,$address,$phone,$website,$email,$token) = $explodeLine;
$data = ['name' => $name, 'address' => $address, 'phone' => $phone, 'website' => >$website, 'email' => $email, 'token' => $token];
$sql = "INSERT INTO localpeople (name, address, phone, website, email, token) VALUES (:name, :address, :phone, :website, :email, :token)";
$stmt= $pdo->prepare($sql);
$stmt->execute($data);
};
fclose($open);
The column 'email' has a unique index.
However, when the duplicate is in the very last row, no error is shown, and the duplicate is simply inserted into the table.
How is that possible ?
I'm guessing it must have something to do with the way fopen reads the .txt file, but I can't find the actual reason (and a solution).
Why can't MySql see the duplicate ?