[英]Relate an input to a button in php
我有一個腳本,它創建一系列輸入和按鈕,並從數據庫中檢索它們,如下所示:
while ($row = mysql_fetch_array($sql)){
echo "<input value='".$row['val']."'/><button type='submit'>delete</button>";
}
該腳本可以檢索數據庫中任意數量的行。 刪除按鈕應該刪除它旁邊的輸入,如下所示:
$sql="DELETE FROM $tbl WHERE ......";
$delete= mysql_query($sql5, $dbh) or die ("there was a problem");
我的問題是...是否可以將每個按鈕與其旁邊的輸入相關聯?
提前致謝!
以您的代碼為起點,進行如下更改:
while ($row = mysql_fetch_array($sql)){
echo "<input value='".$row['val']."'/><button name='delete[" . $row['id'] . "]' type='submit'>delete</button>";
}
然后,將表單發布到哪里,在您的php中:
// Check if the delete button was posted and get the value
$delete = (isset($_POST['delete'])) ? $_POST['delete'] : NULL;
// $delete should contain an array of ids. Iterate over them
foreach((array)$delete AS $id=>$x) {
// NOTE: DO NOT use mysql_ - used here ONLY because your question contains mysql_
$sql="DELETE FROM [table] WHERE id = " . (int)$id;
// Delete the record where the id matches
// Also - on your die, let's SEE the problem, by echoing mysql_error()
$results = mysql_query($sql, $dbh) or die ("there was a problem<br>" . mysql_error());
if ($results) {
// .. code to run if query executed successfully...
}
}
不要使用mysql_
如果不告訴你使用mysql_數據庫擴展是不安全的 ,這是一個壞主意,我不能留下答案。 在PHP 5.5中已棄用。
請參閱選擇數據庫API ,以獲取選擇/切換到mysqli或PDO的幫助。
您不應該這樣使用按鈕並一起輸入。
您可以通過以下方式實現:
while ($row = mysql_fetch_array($sql)){
echo '<input type="submit" name="'.$row['val'].'" value="delete" />";
}
或者,您可以創建許多表單-每個記錄一個,並將輸入類型設置為隱藏。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.