0

I have a text file named attend.txt with following content:

tcs15b021
tcs15b022
tcs15b023
tcs15b011

and here is my php code to insert data into the table named Attendance with following attributes:

CourseId, Date, RollNo, Status where CourseId and Date comes from the html form, RollNo is taken from the attend.txt file and Status is a direct string('Present' or 'Absent').

code

  if(isset($_POST['submit'])){
            $handle = @fopen("attend.txt", "r");
            $CourseId = $_POST[CourseId];
            $Date = $_POST[Date];


            while (!feof($handle)){
                $buffer = fgets($handle, 4096);
                echo $buffer.'<br>';
                $query = "insert into Attendance(CourseId, Date, RollNo, Status) values('$CourseId','$Date', '$buffer', 'Present')";
                $flag = mysqli_query($con, $query);
                if($flag){
                    echo 'Successful!';
                }
                else{
                    echo 'failed!';
                }
            }
        }

The problem with the code is that it inserts only one row i.e, it loops through the while loop but query is executed only once.

any kind of help will be greatly appreciated.

MONU KUMAR
  • 146
  • 2
  • 11
  • INSERT queries accept multiple rows after the VALUES part. It's very inefficent to fire one query per insert. Also, you should be using Prepared Statements. – Gordon Oct 19 '17 at 08:33
  • @Gordon I can't load data directly from file as that file doesn't contain full row but only data from one column – MONU KUMAR Oct 19 '17 at 08:37
  • I didnt say to load data directly. I said you can create a single INSERT query inserting multiple rows. Also: prepared statements! – Gordon Oct 19 '17 at 08:40
  • @Gordon this is not a duplicate. The answers over there doesn't solve my problem. – MONU KUMAR Oct 19 '17 at 12:13
  • Then you need to be more specific about your problem. – Gordon Oct 19 '17 at 12:18
  • I have mentioned clearly that my data is not at the same place but scattered into text file and html form. – MONU KUMAR Oct 19 '17 at 12:21
  • I am not talking about the efficiency. I can't simply understand why the while loop doesn't work as expected. – MONU KUMAR Oct 19 '17 at 12:23
  • You say "it loops through the while loop but query is only executed once". This makes no sense. When it loops through the loop, it will execute the query for each line in the file. How do you know its only executed once? What is the output when you run your code? – Gordon Oct 19 '17 at 12:35
  • I have checked it using flag variable and Insertion is successful only once and rest of the time it fails – MONU KUMAR Oct 19 '17 at 12:59
  • And did you check why it fails via http://php.net/manual/en/mysqli.errno.php or http://php.net/manual/en/mysqli.error-list.php or http://php.net/manual/en/mysqli.error.php – Gordon Oct 19 '17 at 13:14

0 Answers0