0

please in need help in updating multiple rows based on dynamic data fetched from mysql database. I have implemented this using $_Post to udate.php file, but how can i do this using ajax.

//THIS SCRIPT FETCH FROM DATABASE
<body>
    <?php
    mysql_connect("localhost","root","");
    mysql_select_db("student") or die("Unable to select database");

    $sql = "SELECT * FROM students ORDER BY id";

    $result = mysql_query($sql) or die($sql."<br/><br/>".mysql_error());

    $i = 0;

    echo '<table width="50%">';
    echo '<tr>';
    echo '<td>ID</td>';
    echo '<td>Name</td>';
    echo '<td>Address</td>';
    echo '</tr>';

    echo "<form name='form_update' method='post' action='update.php'>\n";
    while ($students = mysql_fetch_array($result)) {
    echo '<tr>';
    echo "<td>{$students['id']}<input type='hidden' name='id[$i]'value='{$students['id']}' /></td>";
    echo "<td>{$students['name']}</td>";
    echo "<td><input type='text' size='40' name='address[$i]' value='{$students['address']}' /></td>";
    echo '</tr>';
    ++$i; 
    }
    echo '<tr>';
    echo "<td><input type='submit' value='submit' /></td>";
    echo '</tr>';
    echo "</form>";
    echo '</table>';
    echo $i; ?>


    </body>

// HERE IS THE UPDATE SCRIPT // On clicking submit all rows are updated but i still cant achieve dis with ajax. UPDATE.PHP

    $size = count($_POST['address']);

    $i = 0;
    while ($i < $size) {
    $address= $_POST['address'][$i];
    $id = $_POST['id'][$i];

    $query = "UPDATE students SET address = '$address' WHERE id = '$id' LIMIT 1";
    mysql_query($query) or die ("Error in query: $query");
    echo "$address<br /><br /><em>Updated!</em><br /><br />";
    ++$i;
}
?>

HERE IS WHAT I HAVE TRIED ON AJAX

function update(){
var j=0;
while(j< <?php echo $i ; ?>){
var id=$("#id" + j);    
var address=$("#address" + j);

$.ajax(
{
url:"update.php",
type:"post",
data:{id:id.val(),address:address.val()},
success:function(response)
{
}
});



}

ANY HELP WILL BE APPRECIATED

4

1 回答 1

0

您不需要循环和执行多个 POST。只需序列化表单数据并将其发送到脚本,例如:

$.ajax({
    url: 'update.php',
    type: 'post',
    data: $('#your-form-id').serialize(), 
    success:function(response){
        // do something
    }
});

此外,您应该考虑修改您的 PHP 以防止 SQL 注入: 如何防止 PHP 中的 SQL 注入?

于 2013-10-14T17:35:03.877 回答