Insert Array Output into Database


Hello Friends now a days i am working on php.A few days ago i got a task from my trainer and task was to uploading a txt file in new folder and output should be in an array format using loops and after that insert that output into database and the content in the text file was 100 email id's.At that time i was new in php and no idea how to start my task and how to use loops.For that i searched on net for many times but i couldn't find the required data to complete task on single site.
So,i had to serach many sites to collect or get idea how to complete my task.Now here in this post i am going to share that program with you so that if you get similar task like this task you can get help from this,i hope it will be helpful to you.

Here the program is:
1) Using this code you can upload your file from one folder to another folder.


<?php
if (($_FILES["file"]["type"] == 'text/plain') && ($_FILES["file"]["size"] < 20000))

  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";


    if (file_exists("nit/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. "."<br/>"."<br/>";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "nit/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "nit/" . $_FILES["file"]["name"]."<br />";
 
      }
    }
  } 
  ?>


2) Use this code after 1st code as shown above, By using this code you will get your output in array format and after that output will be insert into database, see this code how its works,



<?php
        $file = fopen("file.txt", "r");
if ($file) {
  while (!feof($file))
  {
  $aa=fgets($file);
  $explode= explode(",",$aa);
  print_r(explode(',',$aa));
  foreach ($explode as $id =>$email_id)
 {
   $sql="insert into aa (id,email_id) values ('$id','$email_id')";
   $result=mysql_query($sql);
  }
 }
 
fclose($file);
      }
?>
</body>
</html>



Note:- In this above code we are using while loop as well as explode function after that we are using insert statement to insert output into database.

I hope you will find it informative.

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More