从文本文件php mysql将数据插入多行

时间:2013-08-05 03:24:45

标签: php mysql web

我要做的是将文本文件中的每一行插入到mysql数据库的新行中。我做错了什么?

我有一个类似于以下内容的文本文件。

11111,customer1
11112,customer2
11113,customer3
11114,customer4

我的MySQL数据库有字段id,number,customer

我的PHP代码无效,如下所示。

<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!");

    // 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>'; 

    }

    fclose($f);
if (isset($_POST['submit'])) {
include 'connection.php';
$sql="INSERT INTO list (number, customer) VALUES ('$_POST[number]','$_POST[customer]')";
if (!mysqli_query($con,$sql))
  {
  die('Error: ' . mysqli_error());
  }

mysqli_close($con);
}
?>
</table>
<input type="submit" value="Submit File" />
</form>
</body>
</html>

5 个答案:

答案 0 :(得分:4)

您的值位于数组$arrM中,而不在$_POST中。请试试这个:

$sql="INSERT INTO list (number, customer) VALUES ('$arrM[0]','$arrM[1]')";

此外,您还要确保在循环中运行此$sql

答案 1 :(得分:1)

您的代码中存在多个问题。如果您只想从文本文件中插入,可以尝试以下操作

<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而不是获得更好的解决方案。

答案 2 :(得分:0)

您的脚本存在多个问题。

  1. 首先,您使用的是$_POST['submit'],但未在提交按钮中使用name='submit'
  2. 正如@vinod所说,你的值在数组$arrM not in $ _ POST`。
  3. 现在您需要在循环中插入数据。确保只包含一次连接,并在所有数据库操作完成后关闭连接。

    <html>
     <head>
      <title>Add File To DB</title>
     </head>
    
     <body>
      <form action="list.php" method="post">
      <input type="submit" name='submit' value="Submit File" /> <!-- Provide name `submit` to your button so that you can access $_POST['submit'] -->
      <table>
    
      <?php
        $f = fopen("textfile.txt", "r") or exit("Unable to open file!");
    
        //include your connection around here so it is included only once
        include "connection.php";
    
        // 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>'; 
           if (isset($_POST['submit'])) {               
                $sql = "INSERT INTO list (number, customer) VALUES ('$arrM[0]','$arrM[0]')"; //here should be $arrM
                if (!mysqli_query($con,$sql)) {
                  die('Error: ' . mysqli_error());
                }               
            }
        }
    
        fclose($f);
        mysqli_close($con); //close your database connection here
      ?>
     </table>
     <!--<input type="submit" value="Submit File" />-->
     </form>
     </body>
    </html>
    

答案 3 :(得分:0)

If you want to insert data of the text file into the database then you can do this.
<?php   
include('dbcon.php');
$file_content=explode("\n",file_get_contents("demo.txt"));//write your text file name instead of demo.txt   
for($i=0;$i<count($file_content)-1;$i++){
    $exploded_content=explode(",",$file_content[$i]);
    $q=mysqli_query($con,"insert into demo (id,name) values('$exploded_content[0]','$exploded_content[1]')");
         //put your table name instead of demo it has two columns id and name
}

?>
Below is the dbcon.php file
// Create connection
$con=mysqli_connect("localhost","user","pass","dbname");
//put your host user pass database name above i put it dummy
// Check connection
if (mysqli_connect_errno($con))
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

答案 4 :(得分:0)

您必须正确插入值

$sql="INSERT INTO list (number, customer) VALUES ('".$arrM[0]."','".$arrM[1]."')";