如何使用PHP从表中删除MySQL数据库数据

时间:2019-05-14 07:04:41

标签: php mysql

我的PHP代码有问题,无法删除MySQL数据库中的某些数据。我已经尝试了一些不同的方法,但它行不通。

尝试尝试的方法:删除$ productId,将$ producId切换为1、2、3和4。

if (isset($_POST['remove_product'])) {
  $productId = 4

  $sql = "DELETE FROM products WHERE id = '.$productId.'";
  $stmt = mysqli_init($conn);
  if (!mysqli_prepare($stmt, $sql)) {
    header("Location: products.php?error=sqlerror");
    exit();
  } else {
    mysqli_execute($stmt);
  }
}

我想知道它是否可以从MySQL表中删除数据,所以如果有人可以提供解决方案,谢谢:)

谢谢!

3 个答案:

答案 0 :(得分:0)

您缺少分号

$productId = 4
--------------^

使用

$productId = 4;

您在使用引号时遇到一些问题:

$sql = "DELETE FROM products WHERE id = '.$productId.'";  
-------^--------------------------------^------------^^

它应该说:

$sql = "DELETE FROM products WHERE id = " . $productId;

同样,您没有以正确的方式使用准备好的语句

if (isset($_POST['remove_product'])) {
  $productId = 4;

  $sql = "DELETE FROM products WHERE id = ?";
  if (!$stmt = mysqli_prepare($sql)) {
    header("Location: products.php?error=sqlerror");
    exit();
  } else {
    $stmt->bind_params("i", $productId);
    $stmt->execute();
  }
}

答案 1 :(得分:0)

您使用了错误的函数来初始化,准备和执行语句。您应该改用mysqli_stmt_initmysqli_stmt_preparemysqli_stmt_execute。另外,由于您正在准备一条语句,因此应该利用它来避免SQL注入。试试这个:

if (isset($_POST['remove_product'])) {
  $productId = 4;

  $sql = "DELETE FROM products WHERE id = ?";
  $stmt = mysqli_stmt_init($conn);
  if (!mysqli_stmt_prepare($stmt, $sql)) {
    header("Location: products.php?error=sqlerror");
    exit();
  }
  else {
    mysqli_stmt_bind_param($stmt, 'i', $productId);
    mysqli_stmt_execute($stmt);
  }
}

答案 2 :(得分:0)

您的代码中有一些语法错误。使用mysqli-query执行查询。它经常使用

if (isset($_POST['remove_product'])) {
  $productId = 4;

  $sql = "DELETE FROM products WHERE id = ".$productId;
  $stmt = mysqli_init($conn);
  if (!mysqli_query($stmt, $sql)) {
    header("Location: products.php?error=sqlerror");
    exit();
  } else {
    mysqli_execute($stmt);
  }
}

尝试一次