MySQL删除记录

时间:2016-07-17 15:13:19

标签: php mysql web sql-delete

基本上,我的php代码应该从数据库中添加或删除书籍记录。

它将记录添加到数据库,但它删除它们。这是我的代码:

<?php 

require_once "login.php";
// connecting to the MySQL
$db_server = new mysqli($db_hostname,$db_username,$db_password);

if(!$db_server){
    die("Unable to connect MySQL:" . mysql_error());
}
// selecting needed database
mysqli_select_db($db_server,$db_database) or die("Unable to select database:" + mysqli_error());

// Deleting the Record
  if (isset($_POST['delete']) && isset($_POST['author']))
  {
    $author  = $_POST['author'];
    $query = "DELETE FROM classics WHERE year='$author'";
    if (!$db_server->query($query)) 
      echo "DELETE failed: $query<br>" .
      mysql_error() . "<br><br>";
  }

// Adding record to MySQL
  if (isset($_POST['author']) && isset($_POST['title']) && isset($_POST['category']) && isset($_POST['year']))
  {
    $author   = $_POST['author'];
    $title    = $_POST['title'];
    $category = $_POST['category'];
    $year     = $_POST['year'];

    $query = "INSERT INTO classics VALUES" .
      "('$author', '$title', '$category', '$year')";

    if (!$db_server->query($query))
      echo "INSERT failed: $query<br>" .
      mysql_error() . "<br><br>";
  }

  echo <<<_END
  <form action="practise.php" method="post"><pre>
    Author <input type="text" name="author">
     Title <input type="text" name="title">
  Category <input type="text" name="category">
      Year <input type="text" name="year">
           <input type="submit" value="ADD RECORD">
  </pre></form>
_END;
  // Outputing or Fetching the Added Record
  $query  = "SELECT * FROM classics";
  $result = $db_server->query($query);

  if (!$result) die ("Database access failed: " . mysqli_error());
  $rows = mysqli_num_rows($result);

  for ($j = 0 ; $j < $rows ; ++$j)
  {
    $row = mysqli_fetch_row($result);
    echo <<<_END
  <pre>
    Author $row[0]
     Title $row[1]
  Category $row[2]
      Year $row[3]
  </pre>
  <form action="practise.php" method="post">
  <input type="hidden" name="delete" value="yes">
  <input type="hidden" name="year" value="$row[0]">
  <input type="submit" value="DELETE RECORD"></form>
_END;
  }


  mysqli_close($db_server);

?>

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您好error中有if statement。您的condition永远不会获得true,因此您永远不会进入

if statements

你应该使用这个

// you have no author field in delete form use year instead
if (isset($_POST['delete']) && isset($_POST['year']))
  {
    $year  = $_POST['year'];
    $query = "DELETE FROM classics WHERE year='$year'";
    if (!$db_server->query($query)) 
      echo "DELETE failed: $query<br>" .
     mysqli_error(($db_server) . "<br><br>";
  }

我在这里看不到作者字段

<form action="practise.php" method="post">
  <input type="hidden" name="delete" value="yes">
  <input type="hidden" name="year" value="$row[0]">
  <input type="submit" value="DELETE RECORD"></form>