这是我的挑战:
我想用来自$ _POST数组的输入更新MySQL表。
这是怎么做到的? (花几个小时寻找解决方案)。
在我的“table.php”中,我从MySQL获取数据并将其放在输入表单中。
在我的“updatesfields.php”中,我无法弄清楚如何更新MySQL中的字段。 (我可能会离开,但那不是新闻)
Table.php:
<form method="POST" action="updatefields.php" enctype="multipart/form-data" >
<table border="1"><tr>
<td>ID</td>
<td>Text</td>
</tr>
<?php
$host = "xxx";
$username1 = "xxx";
$password1 = "xxx";
$db_name = "xxx";
$tbl_name = "xxx";
$conn = new PDO("mysql:host=$host;dbname=$db_name",$username1,$password1);
$sql = "SELECT * FROM $tbl_name ORDER BY bilag ASC";
$q = $conn->prepare($sql);
$q->execute(array($title));
$q->setFetchMode(PDO::FETCH_BOTH);
// fetch
while($data = $q->fetch()){
echo "<tr><td>";
// --------------------- ID -----------------------------
$id = $data[0];
if ($id != 0)
{ echo "<center><input type='text' style='font-weight:bold;' value='$id' name='id[]' size='10'>";}
else { echo "<center><input type='text' style='font-weight:bold;' value='' name='id[]' size='10'>"; }
echo "</td>";
// --------------------- ID -----------------------------
echo "<td>";
// --------------------- Text -----------------------------
$text = $data[3];
if ($text != null)
{ echo "<center><input type='text' style='font-weight:bold;' value='$text' name='text[]' size='10'>";}
else { echo "<center><input type='text' style='font-weight:bold;' value='' name='text[]' size='10'>"; }
// --------------------- Text -----------------------------
echo "</td></tr>";
}
?>
</table>
<br>
<input type="submit" value="Update">
</form>
updatefields.php:
<?php
$host = "xxx";
$username1 = "xxx";
$password1 = "xxx";
$db_name = "xxx";
$tbl_name = "xxx";
foreach ($_POST as $number => $text)
{
$conn = new PDO("mysql:host=$host;dbname=$db_name",$username1,$password1);
$sql = "UPDATE $tbl_name SET text=? WHERE id=?]";
$q = $conn->prepare($sql);
$q->execute(array($indsæt,$id));
}
?>
答案 0 :(得分:1)
首先,在HTML中,我们需要更改它:
<input type="submit" value="Update">
对此。名称是重要的属性,因为它们成为$ _POST数组中的键。
<input type="submit" name="submit" value="Update">
然后,在updatefields.php中:
if (isset($_POST['submit'])){
//how many ids came through in the $_POST array?
$id_count = count($_POST['id']);
//connect only once, before the loop
$conn = new PDO("mysql:host=$host;dbname=$db_name",$username1,$password1);
//this runs once for each id we have
for ($i=0; $i<$id_count; $i++){
$sql = "UPDATE $tbl_name SET text=? WHERE id=?";
$q = $conn->prepare($sql);
$q->bindParam(1, $_POST['text'][$i]);
$q->bindParam(2, $_POST['id'][$i]);
$q->execute();
if ($q) {//execute() returns TRUE on success
//insert success
} else {
//insert failed
}
}//for loop
} else {//submission did not come from form
echo "There was a problem processing this request. <a href="Table.php">Please click here to try again.</a>";
}
您可以在the PHP documentation中阅读有关绑定参数的更多信息。