PHP & MySQL 6th edition: deletejoke.php

book

#1

Hi guys. I give up... I can't seem to make deletejoke.php work using the code shown in the book.

My "try" block of deletejoke.php looks like this:

  $pdo = new PDO('mysql:host=localhost;dbname=ijdb;charset=utf8', 'ijdbuser', 'P@ssw0rd');
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $sql = 'DELETE FROM `joke` WHERE `id` = :id';
  $stmt = $pdo->prepare($sql);
  $stmt->bindValue(':id', $_POST['id']);
  $stmt->execute();
  header('location: jokes.php');

Page displays fine, I have all the jokes visible, just Delete button doesn't work. Browser seems to do something for less than a second (page does not reload) but still displays same jokes, so nothing gets deleted.

I tried to test it step by step and think the issue is with "bindValue" line.
For example, if I update SQL query to: $sql = 'DELETE FROM joke WHERE id = 5' and comment out the bindValue line, if I will press Delete button on any joke line, joke with ID = 5 will be successfully deleted.

Is my issue with :id or with entire bindValue line?

Thanks!


#2

Neither looks wrong to me, though I tend to use bindParam() rather than bindValue() myself.

What value is in your $_POST variable?

That suggests a problem with your form rather than with the PHP code. Can you show the html for that?


#3

If I put an echo $_POST; in jokes.html.php after the form, I see "Array" string displayed after Delete button.

Got it! Indeed, looking closely at the form, for some reason I gave a different name to the hidden input tag. Changing what I had to below (specifically name="id"), solved the issue:
<input type="hidden" name="id" value="<?php echo $joke['id'] ?>">

Thanks a lot for leading me to the right direction!


#4

Yes, you need to use var_dump() to display an array and its contents.

No problem, glad it helped.


#5

Or print_r()


#6

FYI this is the 5th edition, the code in the 6th edition is quite a lot different.

However, the code itself looks fine try

var_dump($_POST);

and check that $_POST['id'] contains the value you're expecting it to. Also comment out the redirect because you won't see any errors if there are any.


#7

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.