我有一个脚本可以创建一系列输入和按钮,从这样的数据库中检索它们:
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");
我的问题是......有没有办法将每个按钮与旁边的输入相关联?
提前致谢!
答案 0 :(得分:0)
利用您的代码作为起点,进行一些更改:
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_ database extension是个坏主意。它已在PHP 5.5中弃用。
有关选择/切换到mysqli或PDO
的帮助,请参阅Choosing a database API答案 1 :(得分:-1)
你不应该以这种方式一起使用按钮和输入。
你可以这样做:
while ($row = mysql_fetch_array($sql)){
echo '<input type="submit" name="'.$row['val'].'" value="delete" />";
}
或者您可以创建多个表单 - 每个表单一个,并将输入类型设置为隐藏。