0

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.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Steven
  • 93
  • 2
  • 5
  • Is any of value null? – zuro Mar 17 '20 at 12:14
  • You should really, really, really enable error reporting for your development environment. PHP would have gladly tell you what the problem is if you only let it to – Your Common Sense Mar 17 '20 at 12:17
  • none of them is null @zuro – Steven Mar 17 '20 at 12:18
  • @YourCommonSense thank you very very very much. It was actually straight up with me after adding some code to enable error reporting. Being new to PHP I forgot the $ sign when indexing the elements. Thanks – Steven Mar 17 '20 at 12:22

0 Answers0