簡體   English   中英

PHP表單更新mysql數據庫在編輯一條記錄后返回所有數據庫記錄

[英]PHP form update mysql database returns all database records after editing one record

因此,我得到了該代碼,其他Stack成員也幫助我進行了微調和更正了一些錯誤,這些代碼都可以正常工作,但是有一個小細節,在成功編輯一條記錄並單擊更新按鈕后,在數據庫中加載到頁面中。 這是我的代碼如下:

<?php 

$con = mysql_connect("localhost", "root", "M1q2w3e4r");
if (!$con) {
die("Can not connect: " . mysql_error());
}
mysql_select_db("inventory",$con);

if (isset($_POST['update'])){
$UpdateQuery = "UPDATE invoice SET `inv_number`='$_POST[inv_number]', `from_date`='$_POST[from_date]', `to_date`='$_POST[to_date]',`date_type`='$_POST[date_type]', `notes`='$_POST[notes]' WHERE id='$_POST[id]'";               
mysql_query($UpdateQuery, $con);
};

$where = '';
    if(!empty($_GET) && !empty($_GET['edit'])) {
        $where = ' where id='.$_GET['edit'];
    }
    $sql = "SELECT * FROM invoice".$where;

$myData = mysql_query($sql,$con);
echo "<table border=1>
<tr>
<th>Inv #</th>
<th>From</th>
<th>To</th>
<th>Type</th>
<th>Notes</th>
</tr>";
while($record = mysql_fetch_array($myData)){
echo "<form action='edit.php' method='post'>";
echo "<tr>";
echo "<td>" . "<input type='text' name='inv_number' value='" . $record['inv_number'] . "'> </td>";
echo "<td>" . "<input type='text' id='from' name='from_date' value='" . $record['from_date'] . "'> </td>";
echo "<td>" . "<input type='text' id='to' name='to_date' value='" . $record['to_date'] . "'> </td>";
echo "<td>" . "<input type='text' name='date_type' value='" . $record['date_type'] . "'> </td>";
echo "<td>" . "<input type='text' name='notes' value='" . $record['notes'] . "'> </td>";
echo "<td>" . "<input type='hidden' name='id' value='" . $record['id'] . "'> </td>";
echo "<td>" . "<input type='hidden' name='hidden' value='" . $record['id'] . "'> </td>";
echo "<td>" . "<input type='submit' name='update' value='update'>" . " </td>";
echo "</tr>";
echo "</form>";
}

echo "</table>";
mysql_close($con);

?>

我知道這與action =“ edit.php”形式有關,因為它刷新了頁面中URL中的ID號。 所以我嘗試了這個:

echo "<form action='edit.php?edit=<?php echo $_REQUEST["id"]; ?>' method='post'>";

但這只會導致我的edit.php顯示為空白頁。 如果有人可以幫助我找出在單擊更新按鈕后如何防止所有數據庫記錄顯示在頁面中的方法,那將非常有幫助。

例如,如果我只想顯示剛剛更新的記錄,我可以這樣做:

if (isset($_POST['update'])){
    $UpdateQuery = "UPDATE invoice SET `inv_number`='$_POST[inv_number]',    `from_date`='$_POST[from_date]', `to_date`='$_POST[to_date]',`date_type`='$_POST[date_type]', `notes`='$_POST[notes]' WHERE id='$_POST[id]'";               
    mysql_query($UpdateQuery, $con);
    $where = ' where id='.$_POST[id];
}
else {
    $where = '';
    if(!empty($_GET) && !empty($_GET['edit'])) {
        $where = ' where id='.$_GET['edit'];
    }
}

您也可以使用REQUEST而不是GET,並在表單中創建一個名稱為“ edit”的隱藏輸入字段。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM