您的代码中有多个问题。如果您只想从文本文件中插入,可以尝试以下操作
<html>
<head>
<title>Add File To DB</title>
</head>
<body>
<form action="list.php" method="post">
<input type="submit" value="Submit File" />
<table>
<?php
$f = fopen("textfile.txt", "r") or exit("Unable to open file!");
$arr_to_insert = array();
// Read line by line until end of file
while (!feof($f)) {
// Make an array using comma as delimiter
$arrM = explode(',',fgets($f));
// Write links (get the data in the array)
echo '<tr><td name="number">' . $arrM[0] . '</td><td name="customer">' . $arrM[1] . '</td></tr>';
//strore text file row to an array
$arr_to_insert[] = $arrM;
}
fclose($f);
if (isset($_POST['submit'])) {
include 'connection.php';
foreach($arr_to_insert as $ai){
$sql="INSERT INTO list (number, customer) VALUES ('{$ai[0]}','{$ai[1]}')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error());
}
}
mysqli_close($con);
}
?>
</table>
</form>
</body>
</html>
注释了问题的代码的原始版本。
<html>
<head>
<title>Add File To DB</title>
</head>
<body>
<form action="list.php" method="post">
<input type="submit" value="Submit File" />
<table>
<?php
$f = fopen("textfile.txt", "r") or exit("Unable to open file!");
// you need to strore text file row to an array to later insert to database.
// Read line by line until end of file
while (!feof($f)) {
// Make an array using comma as delimiter
$arrM = explode(',',fgets($f)); //$arrM is private inside while loop.
// Write links (get the data in the array)
echo '<tr><td name="number">' . $arrM[0] . '</td><td name="customer">' . $arrM[1] . '</td></tr>';
}
fclose($f);
if (isset($_POST['submit'])) {
include 'connection.php';
//you are trying to insert $_POST[number] and $_POST[customer] which are non-existent
//also you need to loop through the rows in your text file and store each row.
$sql="INSERT INTO list (number, customer) VALUES ('$_POST[number]','$_POST[customer]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error());
}
mysqli_close($con);
}
?>
</table>
<!-- duplicate submit button -->
<input type="submit" value="Submit File" />
</form>
</body>
</html>
PS:请注意,我只是指出您的代码中的错误并按原样进行修复。我不是想优化它。看起来您正在尝试学习 PHP,而不是获得更好的解决方案。