I am trying to read from a file and insert this to a database. But the error message is giving me trouble

Notice: Undefined offset: 1 in C:\xampp\htdocs\test\try2.php on line 15. This is the error message.
On line 15 is: $userName = $tmp[1];

my code is

<?php
mysql_connect("localhost", "root", "")or die("cannot connect");

mysql_select_db("test")or die("cannot select DB");
$file = "test.txt";
$fp = fopen($file, "r");
$data = fread($fp, filesize($file));
fclose($fp);
$delimiter = ".";
$output = explode($delimiter, $data);

foreach($output as $var) {
$tmp = explode("|", $var);
$userId = $tmp[0];
$userName = $tmp[1];

$sql = "INSERT INTO sample SET userId='$userId', userName='$userName'";
mysql_query($sql);
}
?>

Dani AI

Generated

Good catch by . The undefined-offset error comes from indexing a split result that doesn't contain the expected element. To avoid that in future imports, parse the file line-by-line, normalize and validate each line, and never assume an index exists before checking it. Also replace deprecated mysql_* calls with mysqli or PDO and prepared statements for safety and longevity.

A robust pattern (read line, skip blanks, split safely, check parts, then insert) looks like this:

<?php
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'dbuser', 'dbpass', [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);

$fh = fopen('test.txt', 'r');
$stmt = $pdo->prepare('INSERT INTO sample (userId, userName) VALUES (:id, :name)');

while (($line = fgets($fh)) !== false) {
    $line = trim($line);
    if ($line === '') continue;

    // split on any run of whitespace (space or tab)
    $parts = preg_split('/\s+/', $line);
    if (count($parts) < 2) continue; // safe-guard

    $stmt->execute([':id' => $parts[0], ':name' => $parts[1]]);
}
fclose($fh);
?>

Troubleshooting notes: if names may contain spaces, switch to a fixed delimiter (tab/comma) or use an approach that preserves quoted fields (fgetcsv). Remove leading BOMs and normalize CRLF with trim() or str_replace. If a trailing delimiter or extra blank line is present, apply array_filter to drop empty tokens before indexing. Finally, if the thread data is small, file() plus looping over lines is simpler; for large files, stream with fgets() as shown. This keeps parsing predictable and prevents the undefined-offset errors that ran into.

Recommended Answers

All 4 Replies

This simply means that the $var you're trying to split doesn't contain any | at all, therefore the resulting array ($tmp) is only 1 element long and $tmp[1] doesn't exist.

I can input the userid. But I cant insert the username.

my text file contains something like
1 Mike
2 Lisa
3 Holy

If your file looks like that, why are you trying to split on "|" which you know isn't in the file at all?

$tmp = explode(" ", $var);

Should be what you want.

Sorted it out :D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.