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);
}
?>

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.