如何将mysql'id'链接到html元素

时间:2017-07-25 20:16:20

标签: php html mysql

我有一个数据库,其中包含显示在网页上的一些数据行。现在,我正在寻找一种方法将mysql中的每个'ID'字段链接到一个按钮,这样当单击该按钮时,将运行一个php脚本,删除与该ID相关联的mysql信息行。

我知道这是不正确的,但我认为它很接近。只是不知道id标签内的php部分。帮助

<form action="remove.php" method="post">
   <input type="submit" value="Remove Entry" id="<?php $row['id'] ?>" />
</form>

我是否走在正确的道路上? remove.php看起来像......

<?php

$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if($conn === false){
   die("ERROR: Could not connect. " . mysqli_connect_error());
}

$sql = "DELETE from newcars (stock, year, make, model, trim)
        WHERE ('$_POST[id] = $row[id]');

if(mysqli_query($conn, $sql)){
    echo "Records deleted successfully.";
} 

else {
    echo "ERROR: Could not execute $sql. " . mysqli_error($link);
}

mysql_close($conn)
?>

非常感谢任何帮助。 谢谢!

2 个答案:

答案 0 :(得分:3)

HTML:

<form action="remove.php" method="post">
   <input type="hidden" name="id" value="<?php echo (int)$row['id']; ?>">
   <input type="submit" value="Remove Entry" />
</form>

您希望在表单元素中传递ID,而不是使用提交按钮。

PHP看起来像这样 - 这比使用预编译语句比原始代码更安全。

<?php

$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if($conn === false) {
    die("ERROR: Could not connect. " . mysqli_connect_error());
}

$stmt = $conn->prepare("DELETE FROM newcars WHERE id = ?");
// prepare() can fail because of syntax errors, missing privileges, ....
if(false === $stmt) {
    // and since all the following operations need a valid/ready statement object
    // it doesn't make sense to go on
    // you might want to use a more sophisticated mechanism than die()
    // but's it's only an example
    die('prepare() failed: ' . htmlspecialchars($mysqli->error));
}

$rc = $stmt->bind_param('i', $_POST['id']);
// bind_param() can fail because the number of parameter doesn't match the placeholders in the statement
// or there's a type conflict(?), or ....
if(false === $rc) {
    // again execute() is useless if you can't bind the parameters. Bail out somehow.
    die('bind_param() failed: ' . htmlspecialchars($stmt->error));
}

$rc = $stmt->execute();
// execute() can fail for various reasons. And may it be as stupid as someone tripping over the network cable
// 2006 "server gone away" is always an option
if(false === $rc) {
    die('execute() failed: ' . htmlspecialchars($stmt->error));
}

$stmt->close();

//redirect page back to view page
?>

答案 1 :(得分:1)

如果您希望发布您的ID,则应该是这样的:

<form action="remove.php" method="post">
   <input type="hidden" name="id" value="<?php echo (int)$row['id']; ?>">
   <input type="submit" value="Remove Entry" />
</form>

发布名称为id且值为$row['id']的隐藏字段。

你应该注意上面的评论,以避免你的php中的mysql注入。