0

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 ?

Rob
  • 11
  • 4
  • It might be a stray space or other unprintable character. You may want to `trim()` each piece before it is inserted. – Jay Blanchard Jan 14 '20 at 15:22
  • 1
    `fgets` includes the newline character, but behind your last line there probably isn’t one. An email address, and that same email address _plus_ a newline, are not the same thing. `trim()` – 04FS Jan 14 '20 at 15:22
  • Thanks to both of you. Trim() solved the issue. – Rob Jan 14 '20 at 16:28

0 Answers0