繁体   English   中英

将输入与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>";
}

该脚本可以检索数据库中任意数量的行。 删除按钮应该删除它旁边的输入,如下所示:

$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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM