"> "> -6ren">
gpt4 book ai didi

php mysql批量记录更新?

转载 作者:行者123 更新时间:2023-11-29 00:49:03 24 4
gpt4 key购买 nike

我正在尝试使用以下代码更新多个 mysql 记录:

<strong>Update multiple rows in mysql</strong><br> 

<?php
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
$tbl_name="test_mysql"; // 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 $tbl_name";
$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>Lastname</strong></td>
<td align="center"><strong>Email</strong></td>
</tr>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td align="center"><? $id[]=$rows['id']; ?><? echo $rows['id']; ?></td>
<td align="center"><input name="name[]" type="text" id="name" value="<? echo $rows['name']; ?>"></td>
<td align="center"><input name="lastname[]" type="text" id="lastname" value="<? echo $rows['lastname']; ?>"></td>
<td align="center"><input name="email[]" type="text" id="email" value="<? echo $rows['email']; ?>"></td>
</tr>
<?php
}
?>
<tr>
<td colspan="4" align="center"><input type="submit" name="Submit" value="Submit"></td>
</tr>
</table>
</td>
</tr>
</form>
</table>
<?php
// Check if button name "Submit" is active, do this
if($Submit){
for($i=0;$i<$count;$i++){
$sql1="UPDATE $tbl_name
SET name='$name[$i]',
lastname='$lastname[$i]',
email='$email[$i]'
WHERE id='$id[$i]'";
$result1=mysql_query($sql1);
}
}

if($result1){
header("location:update_multiple.php");
?>

它在输入文本框中显示来自数据库的记录,但是当我用新记录更改旧记录然后提交时,没有任何反应,页面刷新为旧值。

最佳答案

您需要使用 $_POST['Submit'] 检查表单是否已提交。您还可以使用隐藏的输入字段来跟踪要更新的每一行:

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

然后在处理你的提交时你应该做这样的事情:

if(isset($_POST['Submit'])) {
$ids = $_POST['id'];
$names = $_POST['name'];
$lastnames = $_POST['lastname'];
$emails = $_POST['email'];
//
foreach($ids as $id) {
// update the record based on the id and supplied data
}
}

当然,更新过程应该在您从数据库中检索行之前执行。换句话说,上面的代码应该放在脚本的顶部附近。至少在:

$sql="SELECT * FROM $tbl_name";
$result=mysql_query($sql);

关于php mysql批量记录更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9275545/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com