将输入与php中的按钮关联起来


Relate an input to a button in php

我有一个脚本,创建一系列输入和按钮,从数据库中检索它们,如下所示:

while ($row = mysql_fetch_array($sql)){
echo "<input value='".$row['val']."'/><button type='submit'>delete</button>";
}

这个脚本可以从数据库中检索任意数量的行。delete按钮应该删除它旁边的输入,就像这样:

$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以获得选择/切换到mysql或PDO的帮助

你不应该这样同时使用按钮和输入。

你可以这样做:

while ($row = mysql_fetch_array($sql)){
  echo '<input type="submit" name="'.$row['val'].'" value="delete" />";
}

或者您可以创建多个表单-每个记录一个表单,并将输入类型设置为隐藏