PHP MYSQL

HOW TO IMPORT CSV IN PHP MYSQL

DUMMY USER TABLE user_id | INT(11) | PRIMARY KEY user_email | VARCHAR(255) user_name | VARCHAR(255)

DUMMY CSV USERS job@doe.com | Job Doe jon@doe.com | Jon Doe joy@doe.com | Joy Doe

DUMMY TABLE & CSV FILE

01

<form action="import.php" method="post"    enctype="multipart/form-data">   <input type="file" name="upcsv"    accept=".csv" required/>   <input type="submit" value="Upload"/> </form>

CSV FILE UPLOAD FORM

02

PHP IMPORT CSV FILE (PART 1)

03

CONNECT TO DATABASE $pdo = new PDO(   "mysql:host=HOST;dbname=NAME;   charset=$dbChar", USER, PASSWORD);

OPEN UPLOADED CSV $fh = fopen($_FILES["upcsv"]["tmp_name"], "r"); if ($fh === false) { exit("ERROR"); }

IMPORT ROW-BY-ROW while (($row = fgetcsv($fh)) !== false) {   $stmt = $pdo->prepare("INSERT    INTO `users`  (`user_name`,    `user_email`) VALUES (?,?)");   $stmt->execute([$row[0], $row[1]]); } fclose($fh);

PHP IMPORT CSV FILE (PART 2)

04