How to validate email in csv file

Viewed 215

I have a csv file that I parse and display it by storing it in an array. I was wondering how can I validate the mail or make sure it's the right format before inserting it into mysql? And, if the mail is not validate it should display an error and not insert that row to mysql.

I know I can use that filter_var($email, FILTER_VALIDATE_EMAIL) !== false; but I am not sure how to use it in my code as it is inside an array (the value of email). Any help is appreciated.

My code:

<?php 
require "database.php";

$lines = file('users.csv', FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);
$csv = array_map('str_getcsv', $lines);
$col_names = array_shift($csv);

$users = [];
try {
$stmt = $dbh->prepare("INSERT INTO users(name, surname, email) 
VALUES(:name, :surname, :email)");
foreach($csv as $row) {
    $users[] = [
        $col_names[0] => ucfirst(strtolower($row[0])),
        $col_names[1] => ucfirst(strtolower($row[1])),
        $col_names[2] => strtolower(strtolower($row[2])), //that's the mail
    ];
    $stmt->bindValue(':name', $col_names[0], PDO::PARAM_STR);
    $stmt->bindValue(':surname', $col_names[1], PDO::PARAM_STR);
    $stmt->bindValue(':email', $col_names[2], PDO::PARAM_STR);
    $stmt->execute();
   
}
}catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
$dbh = null;

?>
1 Answers

You can simply check it within your loop something like below

foreach($csv as $row) {

if (filter_var(strtolower(strtolower($row[2])), FILTER_VALIDATE_EMAIL) === false) {
  echo("".strtolower($row[2]))." is not a valid email address"); // You can break the loop and return from here
}

    $users[] = [
        $col_names[0] => ucfirst(strtolower($row[0])),
        $col_names[1] => ucfirst(strtolower($row[1])),
        $col_names[2] => strtolower(strtolower($row[2])), //that's the mail
    ];
    $stmt->bindValue(':name', $col_names[0], PDO::PARAM_STR);
    $stmt->bindValue(':surname', $col_names[1], PDO::PARAM_STR);
    $stmt->bindValue(':email', $col_names[2], PDO::PARAM_STR);
    $stmt->execute();
   
}

Apart from this I would suggest you to create a batch insert for this.. Never execute the insertion query in a loop

Related