如何在php中更新多行

时间:2013-09-21 07:13:12

标签: php mysql

 <?php
    $host="localhost"; // Host name 
    $username="xxxx"; // Mysql username 
    $password="xxxx"; // Mysql password 
    $db_name="xxxx"; // Database name 
    $tbl_name="xxxx"; // Table name 

    // Connect to server and select databse.
    mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
    mysql_select_db("$db_name")or die("cannot select DB");

    $sql="SELECT * FROM xxxx WHERE branch = 'xx' AND xxxx.semester=x ORDER BY xxxx.xxxx";
    $result=mysql_query($sql);

    // Count table rows 
    $count=mysql_num_rows($result);
    ?>

    <table width="500" border="0" cellspacing="1" cellpadding="0">
    <form name="form1" method="post" action="">
    <tr> 
    <td>
    <table width="500" border="0" cellspacing="1" cellpadding="0">


    <tr>
    <td align="center"><strong>Id</strong></td>
    <td align="center"><strong>Name</strong></td>
    <td align="center"><strong>may_tc_s1</strong></td>
    <td align="center"><strong>may_ac_s1</strong></td>
    </tr>
    <?php
    // Check if button name "submit" is active, do this 
    if (isset($_POST['Submit'])) {
        $name = $_POST['name'];
        $lastname = $_POST['lastname'];
        $email = $_POST['email'];
    for($i=0;$i<$count;$i++){
    $sql1="UPDATE $tbl_name SET xxx='$name[$i]', xxx='$lastname[$i]', xxx='$email[$i]' WHERE xxx='$id[$i]'";
    $result1=mysql_query($sql1);
    }
    }
    if(isset($result1)){
    header("location:try.php");
    }
    ?>
    <?php
    while($rows=mysql_fetch_array($result)){
    ?>
    <tr>
    <td align="center"><?php $id[]=$rows['idatten']; ?><?php echo $rows['idatten']; ?></td>
    <td align="center"><input name="name[]" type="text" id="name" value="<?php echo $rows['username']; ?>"></td>
    <td align="center"><input name="lastname[]" type="text" id="lastname" value="<?php echo $rows['may_tc_s1']; ?>"></td>
    <td align="center"><input name="email[]" type="text" id="email" value="<?php echo $rows['may_ac_s1']; ?>"></td>
    </tr>
    <?php
    }
    ?>
    <tr>
    <td colspan="4" align="center"><input type="submit" name="submit" value="Submit"></td>
    </tr>
    </table>
    </td>
    </tr>
    </form>
    </table>

我能够在文本字段中看到记录,但是输入了新记录 值没有得到更新????? 这个代码有什么问题????? 尝试了各种方法,无法找到任何正确的方法???

2 个答案:

答案 0 :(得分:2)

参考此代码:

extract($_POST);
if (isset($Submit)) 
 {
  for($i=0;$i<$count;$i++)
   {
    $update=("UPDATE tbl_name SET name='$name[$i]', lname='$lastname[$i]',email='$email[$i]' WHERE id='$id[$i]'");
    $res=mysql_query($update);
   }
 }
 if(isset($res))
  {
   header("location:try.php");
  }
?>
<?php
while($rows=mysql_fetch_array($result)){
?>

答案 1 :(得分:1)

您没有正确引用变量。

$sql1 = "UPDATE $tbl_name SET xxx='".$name[$i]."', xxx='".$lastname[$i]."', xxx='".$email[$i]."' WHERE xxx='".$id[$i]."'";