Habil Ganbarli Habil Ganbarli - 4 months ago 33
SQL Question

MySQL delete record

So basically, my php code is supposed to add or delete book records from the database.

It adds the records to database, however it does not delete them. Here is my code:

<?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);

?>


Any thoughts?

Answer

Hi You have error in your if statement . your condition never gets true so you are never inside of

if statements

you should use this

// 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>";
  }

I can't see author field here

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