John Y. Semo
John Y. Semo

Reputation: 15

How to Insert to database from loop Using PHP?

The problem occurs when I insert without data. So I want your help in solving this problem.

This is my file: students.php

        <form id="student_form" method="POST"   action="">
<?php
    if(mysql_num_rows($q)>0){           

                ?>


    <table   border="0" dir="ltr" align="center"cellpadding='0' cellspacing='0' >

        <tr> <th>Student ID</th><th>Name</th><th>AVG</th><th>Joining Year</th><th>Message</th><th>Sending Message</th> </tr>

        <?php while($row = mysql_fetch_array($q)){ ?>
        <tr>

            <td id="stud_id[]"> <?php echo $row['studant_ID']; ?></td>
            <td> <?php echo $row['studant_Name']; ?></td>
            <td> <?php echo $row['Average']; ?></td>
            <td> <?php echo $row['year']; ?></td>
            <td> <input id="message1[]" name="message1[]" type="text" size="25px" /></td>
            <td><input name="submit[]" id="submit[]" type="submit"  value="Send"  /> </td>
        </tr>

<?php }}

and this is my insert file: insert_message.php

if (isset($_POST['message1']) && $_POST['message1']!='') {

            $addss = mysql_real_escape_string($_POST['message1']);
        } 

if (isset($_POST['stud_id']) && $_POST['stud_id']!='') {

            $std_id = mysql_real_escape_string($_POST['stud_id']);
        }        


//####################################################################### 

 $query1 = "INSERT INTO `message` (`rcvrid`, `senderid`, `msg`) VALUES ('$std_id', '22011111', '$addss'); ";
 mysql_query($query1);

I connect between two file by jquery and ajax.

<script>

 $("#student_form").on("submit", function(event) {
                event.preventDefault();
                $.ajax({
                    type: "POST",
                    url: "insert_message.php",
                    data: $(this).serialize(),
                    success: function(data) {
                        $("#inner_contant").append(data+"<br/>");//instead this line here you can call some function to read database values and display
                    },
                });
            });


</script>

Upvotes: 1

Views: 108

Answers (2)

madalinivascu
madalinivascu

Reputation: 32354

Remove the form from the page

<tr>

            <td id="stud_id"> <?php echo $row['studant_ID']; ?>
              <input type="hidden" name="stud_id" value="<?php echo $row['studant_ID']; ?>"/>
            </td>
            <td> <?php echo $row['studant_Name']; ?></td>
            <td> <?php echo $row['Average']; ?></td>
            <td> <?php echo $row['year']; ?></td>
            <td> <input id="message1" name="message1" type="text" size="25px" /></td>
            <td><button class="submit" type="submit" />Send </button> </td>
        </tr>

second: your js should look like this:

$(".submit").on("click", function(event) {
                event.preventDefault();
                $.ajax({
                    type: "POST",
                    url: "insert_message.php",
                    data: {stud_id:$(this).closest('tr').find('input[name="stud_id"]').val(),message1:$(this).closest('tr').find('input[name="message1"]').val()},
                    success: function(data) {
                        $("#inner_contant").append(data+"<br/>");//instead this line here you can call some function to read database values and display
                    },
                });
            });

In insert_message.php you need to echo a message to see if you where succesful in updating the database

echo json_encode(array('message'=>'Data updated/Error'));

Upvotes: 1

u_mulder
u_mulder

Reputation: 54841

First of all - all data passed to server in a $_POST array is taken from input fields with name attribute (unless you have some custom js handlers).

So

<td id="stud_id[]"> <?php echo $row['studant_ID']; ?></td>

does nothing.

If you want to store studant_ID somehow - use hidden field for example:

<td>
    <input type="hidden" name="stud_id[]" value="<?php echo $row['studant_ID']; ?>" />
</td>

Next - what do you want from this buttons:

<input name="submit[]" id="submit[]" type="submit" value="Send" />

As they are all belong to one form they will do the same - send all fields to server. If you want every submit button send to server only a pair student_id, message you have to create a form for each pair (or do some js-handlers). Otherwise, on your server you'll have:

  • $_POST['stud_id'] array of all students ids from form
  • $_POST['message1'] array of all messages from form

If you want to process them all - do a foreach:

foreach ($_POST['stud_id'] as $key => $id) {
     // find the message
     $msg = $_POST['message1'][$key];
     $query1 = "INSERT INTO `message` (`rcvrid`, `senderid`, `msg`)    VALUES ('$id', '22011111', '$msg'); ";
     mysql_query($query1);
}

And of course you should remove mysql_ functions and use newer apis - PDO or mysqli

Upvotes: 1

Related Questions