Update: my code works if I put my database file in script file, so not sure why is it not working if I have different file
I have a csv file that I parse at input as in command line and use that file (csv) to insert those values of csv (name, surname and email) to mysql. When I run my code it keep printing over and over until it runs out of memory connected to database
what am I doing wrong? ANy help is appreciated.
script.php
<?php
require "database.php";
$options = ['file:'];
$values = getopt(null, $options);
$lines = file($values['file'], FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);
$csv = array_map('str_getcsv', $lines);
$col_names = array_shift($csv);
$users = [];
foreach($csv as $row) {
$users[] = [
$col_names[0] => ucfirst(strtolower($row[0])),
$col_names[1] => ucfirst(strtolower($row[1])),
$col_names[2] => filter_var(strtolower($row[2]), FILTER_VALIDATE_EMAIL),
];
$stmt = $dbh->prepare("INSERT INTO users(name, surname, email)
VALUES(:name, :surname, :email)");
$stmt->bindParam(':name', $col_names[0]);
$stmt->bindParam(':surname', $col_names[1]);
$stmt->bindParam(':email', $col_names[2]);
$stmt->execute();
}
$dbh = null;
?>
database.php
<?php
$hostname = 'localhost';
$username = 'root';
$password = 'yourpasswordhere';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=userDetails", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'Connected to Database';
} catch (PDOException $e) {
echo $e->getMessage();
}
?>