I am writhing PHP and using phpMyAdmin MySQL database. I am reading data from a text file and writing it to the database but I am getting an error along the process.
The userData.txt looks like this
name1,surname1,suname1@xample.com,paaswwrfdg
name2,surname2,suname2@xample.com,23eferj3uje
name3,surname3,suname3@xample.com,gsfdfgdfgddd
In the initDB.php file, after connecting to the database, I extracted the data from the userData.txt file like this
$values = array();
$file = fopen('userData.txt', 'r');
while ($line = fgets($file)){
$parts = explode(',', $line);
$values[] = "('$parts[0]', '$parts[1]', '$parts[2]', '$parts[3]')";
}
fclose($file);
Then finally I write an SQL query to insert the data to the tbl_User table like this
$sql = "insert into tbl_User (FName, LName, Email, Password) values ";
for ($i = 0; $i < count($values); $i++){
$sql .= $values[i];
if ($i == count($values) - 1){
$sql .= ";";
} else {
$sql .= ",";
}
}
echo $sql;
if ($connection->query($sql) === true){
echo "data captured";
} else {
echo "not captured : " . $connection->error;
}
After some attempts to debug, I found that when I echo $sql
I get this insert into tbl_User (FName, LName, Email, Password) values ,,;
and obviously this error after the query runs not captured : You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ',' at line 1
I do not understand why the variable $sql
is not concatenating the values from $values
array, please assist.