Confirm Delete solution - chapter 7 - PHP and MySQL Novice to Ninja

Dear Kevin,

Could you post the solution for the “Confirm on Delete” challenge, so I can what I have done is correct.

Thanks,

Regards,

Ronnie

Hi Ronnie 2013,

Welcome to the forums.

There isn’t a hard and fast solution to the exercise, so why don’t you post what you have coded and ask for feedback.

Ronnie 2013, you can use a simple javascript to achieve what you want.
Use this: <input type=“submit” name=“action” value=“Delete” onclick=“return confirm(‘Delete This User?’)” />

Well, since nobody answered, here is my attempt - which has failed. It says that “$author[‘id’]” on the third line is undefined.

//to confirm and delete an author from the joke databank
if (isset($_POST['action']) and $_POST['action'] == 'Delete')
{
	$authordeleteid = $author['id'];
	include 'confirmdeleteauthor.html.php';
	exit();
}

if (isset($_POST['connfirmdeleteauthor']))
{
  include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php';

  // Get jokes belonging to author
  try
  {
    $sql = 'SELECT id FROM joke WHERE authorid = :id';
    $s = $pdo->prepare($sql);
    $s->bindValue(':id', $_POST['id']);
    $s->execute();
  }
  catch (PDOException $e)
  {
    $error = 'Error getting list of jokes to delete.';
    include 'error.html.php';
    exit();
  }

  $result = $s->fetchAll();

  // Delete joke category entries
  try
  {
    $sql = 'DELETE FROM jokecategory WHERE jokeid = :id';
    $s = $pdo->prepare($sql);

    // For each joke
    foreach ($result as $row)
    {
      $jokeId = $row['id'];
      $s->bindValue(':id', $jokeId);
      $s->execute();
    }
  }
  catch (PDOException $e)
  {
    $error = 'Error deleting category entries for joke.';
    include 'error.html.php';
    exit();
  }

  // Delete jokes belonging to author
  try
  {
    $sql = 'DELETE FROM joke WHERE authorid = :id';
    $s = $pdo->prepare($sql);
    $s->bindValue(':id', $_POST['id']);
    $s->execute();
  }
  catch (PDOException $e)
  {
    $error = 'Error deleting jokes for author.';
    include 'error.html.php';
    exit();
  }

  // Delete the author
  try
  {
    $sql = 'DELETE FROM author WHERE id = :id';
    $s = $pdo->prepare($sql);
    $s->bindValue(':id', $_POST['id']);
    $s->execute();
  }
  catch (PDOException $e)
  {
    $error = 'Error deleting author.';
    include 'error.html.php';
    exit();
  }

  header('Location: .');
  exit();
}

I think you’ll want to use $_POST[‘id’] where you have $author[‘id’].

Thanks, that did it! Seems to be other problems with my solution but I’m working my way through it.

Great. As you get stuck, don’t hesitate to ask us for help. We’re more than willing :smiley:

hi everyone, I’m having the same problem completing this task or i think it is. i get an error of

Notice: Undefined index: id in C:\xampp\htdocs\php_sandbox\chapter7\admin\authors\index.php on line 22
Any pointers would be great and deeply appreciated. This is what i’ve done so far:


<?php
//Display author list
include $_SERVER['DOCUMENT_ROOT'].'/includes/db.inc.php';
try
{
	$result = $pdo->query('SELECT id, name FROM author');
}
catch(PDOException $e)
{
	$error = 'Error fetching authors from the database!';
	include 'error.html.php';
	exit();
}

foreach($result as $row)
{
	$authors[] = array('id'=> $row['id'], 'name'=> $row['name']);	
}

if( isset($_POST['action']) and $_POST['action'] == 'Delete'){
	
	$authorId = $authors['id'];
	include 'confirmdelete.html.php';
	
	if( $_POST['action'] == 'no' ){
		header('Location:authors.html.php');
		exit();
	}else{
		if(isset($_POST['action']) and $_POST['action'] == 'Delete')
		{
			include $_SERVER['DOCUMENT_ROOT'].'/includes/db.inc.php';
			
			try
			{
				$sql = 'SELECT id from joke where authorId = :id';
				$s = $pdo-> prepare($sql);
				$s -> bindValue(':id', $_POST['id']);
				$s -> execute();
			}catch(PDOException $e){
				$error = 'Error getting list of jokes to delete.'. $e->getMessage();
				include 'error.html.php';
				exit();
			}
			
			$result = $s->fetchAll();
			//delete joke category entries
			try
			{
				$sql='DELETE FROM jokecategory WHERE id=:id';
				$s= $pdo-> prepare($sql);
				//foreach joke category entries
				foreach( $result as $row){
					$jokeId = $row['id'];
					$s-> bindValue(':id', $jokeId);
					$s -> execute();
				}
			}
			catch( PDOException $e )
			{
				$error = 'Error deleting category entries for joke';
				include 'error.html.php';
				exit();
			}
			//delete jokes belonging to author
			try
			{
				$sql='DELETE FROM joke where authorId=:id';
				$s = $pdo-> prepare($sql);
				$s -> bindValue(':id', $_POST['id']);
				$s-> execute();
			}
			catch(PDOException $e)
			{
				$error = 'Error delete jokes from author';
				include 'error.html.php';
				exit();
			}
			
			//delete the author
			try
			{
				$sql = 'DELETE FROM author WHERE id = :id';
				$s = $pdo-> prepare($sql);
				$s-> bindValue(':id', $_POST['id']);
			}
			catch(PDOException $e)
			{
				$error = 'Error deleting author.';
				include 'error.html.php';
				exit();
			}
			header('Location:.');
			exit();
		}

	}
}

include 'authors.html.php';
?>

and then in my 'confirmdelete.html.php i have the following :


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Confirm Delete Page</title>
</head>

<body>
<form action="" method='post'>
	<h1>Are you Sure you want to delete this author?</h1>
    <input type='submit' name='action' value='Yes'/>
    <input type="submit" name="action" value="No" />
    <input type="hidden" name="id" value="<?php $authorId; ?>"    
</form>
</body>
</html>

I’m not sure if this is it, but your hidden input tag is incomplete.

You have:

<input type="hidden" name="id" value="<?php $authorId; ?>"  

It should be: (also you are missing the term echo in front of $authorId)

<input type="hidden" name="id" value="<?php echo $authorId; ?>" />

thanks for spotting that but unfortunately that did not solve it. i’ve tried setting the

$authorid = $_POST['id']

but thishasn’t worked either.

Okay, let’s start from step one. So you have a list of authors on a page, you click Delete and get the confirmation page. Good so far?

  1. Can you provide the output HTML for the confirmation page?
  2. Did the input hidden field for ‘id’ get populated? (It isn’t empty)

Lastly, another bug in your code (I think). Find my comment in the below code

if( isset($_POST['action']) and $_POST['action'] == 'Delete'){
    
    $authorId = $authors['id'];
    include 'confirmdelete.html.php';
    
    if( $_POST['action'] == 'no' ){
        header('Location:authors.html.php');
        exit();
    }else{
        if(isset($_POST['action']) and $_POST['action'] == 'Yes') // cpradio - Since this is confirming the Delete, and the values for action are Yes or No, this needs to be Yes
        {
            include $_SERVER['DOCUMENT_ROOT'].'/includes/db.inc.php';
            
            try
            {
                $sql = 'SELECT id from joke where authorId = :id';
                $s = $pdo-> prepare($sql);
                $s -> bindValue(':id', $_POST['id']);
                $s -> execute();
            }catch(PDOException $e){
                $error = 'Error getting list of jokes to delete.'. $e->getMessage();
                include 'error.html.php';
                exit();
            }
            
            $result = $s->fetchAll();
            //delete joke category entries
            try
            {
                $sql='DELETE FROM jokecategory WHERE id=:id';
                $s= $pdo-> prepare($sql);
                //foreach joke category entries
                foreach( $result as $row){
                    $jokeId = $row['id'];
                    $s-> bindValue(':id', $jokeId);
                    $s -> execute();
                }
            }
            catch( PDOException $e )
            {
                $error = 'Error deleting category entries for joke';
                include 'error.html.php';
                exit();
            }
            //delete jokes belonging to author
            try
            {
                $sql='DELETE FROM joke where authorId=:id';
                $s = $pdo-> prepare($sql);
                $s -> bindValue(':id', $_POST['id']);
                $s-> execute();
            }
            catch(PDOException $e)
            {
                $error = 'Error delete jokes from author';
                include 'error.html.php';
                exit();
            }
            
            //delete the author
            try
            {
                $sql = 'DELETE FROM author WHERE id = :id';
                $s = $pdo-> prepare($sql);
                $s-> bindValue(':id', $_POST['id']);
            }
            catch(PDOException $e)
            {
                $error = 'Error deleting author.';
                include 'error.html.php';
                exit();
            }
            header('Location:.');
            exit();
        }

    }
}

To answer your first quesiton yes and no, in the sense that it does not go to a new page but pastes the confirmation page at the top of the index.php page. I hope that is correct?
This is the html for the confirmation page and the revised code in relation to the changes u suggested in the previous post is directly below.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Confirm Delete Page</title>
</head>

<body>
<form action="" method='post'>
	<h1>Are you Sure you want to delete this author?</h1>
    <input type='submit' name='action' value='Yes'/>// cpradio - Since this is confirming the Delete, and the values for action are Yes or No, this needs to be Yes
    <input type="submit" name="action" value="No" />
    <input type="hidden" name="id" value="<?php $authorId; ?>"/> 
</form>
</body>
</html>


<?php
//Display author list
include $_SERVER['DOCUMENT_ROOT'].'/includes/db.inc.php';
try
{
	$result = $pdo->query('SELECT id, name FROM author');
}
catch(PDOException $e)
{
	$error = 'Error fetching authors from the database!';
	include 'error.html.php';
	exit();
}

foreach($result as $row)
{
	$authors[] = array('id'=> $row['id'], 'name'=> $row['name']);	
}

if( isset($_POST['action']) and $_POST['action'] == 'Delete'){
	
	$authorId = $_POST['id'];
	include 'confirmdelete.html.php';
	
	if( $_POST['action'] == 'No' ){
		header('Location:authors.html.php');
		exit();
	}else{
		if(isset($_POST['action']) and $_POST['action'] == 'Yes')
		{
			include $_SERVER['DOCUMENT_ROOT'].'/includes/db.inc.php';
			
			try
			{
				$sql = 'SELECT id from joke where authorId = :id';
				$s = $pdo-> prepare($sql);
				$s -> bindValue(':id', $_POST['id']);
				$s -> execute();
			}catch(PDOException $e){
				$error = 'Error getting list of jokes to delete.'. $e->getMessage();
				include 'error.html.php';
				exit();
			}
			
			$result = $s->fetchAll();
			//delete joke category entries
			try
			{
				$sql='DELETE FROM jokecategory WHERE id=:id';
				$s= $pdo-> prepare($sql);
				//foreach joke category entries
				foreach( $result as $row){
					$jokeId = $row['id'];
					$s-> bindValue(':id', $jokeId);
					$s -> execute();
				}
			}
			catch( PDOException $e )
			{
				$error = 'Error deleting category entries for joke';
				include 'error.html.php';
				exit();
			}
			//delete jokes belonging to author
			try
			{
				$sql='DELETE FROM joke where authorId=:id';
				$s = $pdo-> prepare($sql);
				$s -> bindValue(':id', $_POST['id']);
				$s-> execute();
			}
			catch(PDOException $e)
			{
				$error = 'Error delete jokes from author';
				include 'error.html.php';
				exit();
			}
			
			//delete the author
			try
			{
				$sql = 'DELETE FROM author WHERE id = :id';
				$s = $pdo-> prepare($sql);
				$s-> bindValue(':id', $_POST['id']);
			}
			catch(PDOException $e)
			{
				$error = 'Error deleting author.';
				include 'error.html.php';
				exit();
			}
			header('Location:.');
			exit();
		}

	}
}

include 'authors.html.php';
?>

In your confirmation file, you still have

<input type="hidden" name="id" value="<?php $authorId; ?>"/> 

When you meant to have (notice the adding of echo)

<input type="hidden" name="id" value="<?php echo $authorId; ?>"/> 

it is at times like this i feel like i just want to…obviously not echoing out the id means it won’t display the id. I wonder how i missed that.
Thank you very much i feel like playing the happy song by pharel right now.

The most obvious mistakes are usually the ones that are hardest to find.

Our brains show us what we expect to see there because we’ve been staring at it so long. Give it to someone new to look at it, and it is glaringly obvious to them. Always be will to pair review your code with someone else, it will save your hide many times in the future :slight_smile:

thank you very much for the advise, one more question though when i do a

var_dump ( $_POST['Id]');

i get a string of 1. I was expecting an int value. do you know why this may be happening.

Yep, PHP is a loosely type language so all input is a string (well this is true for most internet languages; input being strings), so you’d have to manually cast it.

$id = (int)$_POST['id'];

However, since the book has you using prepared statements, you technically do not need to cast it because the prepared statement will do it for you.

$s -> bindValue(':id', $_POST['id']);

You can also specify the type you want it converted too as well.

$s -> bindValue(':id', $_POST['id'], PDO::PARAM_INT);

Thanks once again for clearing that up