Deletejoke chapter 4 of php mysql novice to ninja 5th

hello everyone,

im doing the deletejoke of chapter 4 , and my code is quite the same the source code of the book, but i dont know why it doesnt work. Could anyone please help me? Here ist my Code

index.php

if (get_magic_quotes_gpc())
{
  $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
  while (list($key, $val) = each($process))
  {
    foreach ($val as $k => $v)
    {
      unset($process[$key][$k]);
      if (is_array($v))
      {
        $process[$key][stripslashes($k)] = $v;
        $process[] = &$process[$key][stripslashes($k)];
      }
else {
        $process[$key][stripslashes($k)] = stripslashes($v);
      }
} }
  unset($process);
}

//if the use klick the link ?addjoke from jokes.html.php

if(isset($_GET['addjoke'])){
    include 'form.html.php';
    exit();
}

//configuring the Connection with MySQL database

try
{
$pdo = new PDO('mysql:host=localhost; dbname=ijdb', 'ijdbuser', 'mypassword');
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $pdo->exec('SET NAMES "utf8"');
}
catch (PDOException $e)
{
  $error = 'Unable to connect to the database server.' . $e->getMessage();
  include 'error.html.php';
  exit();
}

//add new joketext

if (isset($_POST['joketext'])){
    try{
        $sql = 'INSERT INTO joke SET
                joketext = :joketext;
                jokedate = CURDATE()';
              
        $s = $pdo->prepare($sql);
        $s->bindValue(':joketext', $_POST['joketext']);
        $s->execute();
                
    } catch (PDOException $e) {
        $error = 'Error adding submitted joke: ' . $e->getMessage();
        include 'error.html.php';
        exit();
    }
    
    header('Location: .');
    exit();
}



if (isset($_GET['deletejoke'])){
    try{
        $sql = 'DELETE FROM joke WHERE id = :id';
        $s = $pdo->prepare($sql);
        $s->bindValue(':id', $_POST['id']);
        $s->execute();
    } catch (PDOException $e) {
        $error = 'Error deleting joke: ' . $e->getMessage();
        include 'error.html.php';
        exit();
    }
    
    header('Location: .');
    exit();
}

try{
    $sql = 'SELECT id, joketext FROM joke';
    $result = $pdo->query($sql);
} catch (PDOException $e) {
    $error = 'Error fetching jokes: ' . $e->getMessage();
    include 'error.html.php';
    exit();
}

while($row = $result->fetch()){
    $jokes[]= array('id' => $row['id'], 'text' => $row['joketext'] );
    
}

include 'jokes.html.php';

jokes.html.php

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Script output</title>
  </head>
  <body>
      
      <!--Add new joke -->
      <p><a href="?addjoke">Add your own joke</a></p>
      <p>Here are all the jokes in the database:</p>
      <?php foreach($jokes as $jAdd): ?>
        <blockquote>
            <p><?php echo htmlspecialchars($jAdd, ENT_QUOTES, 'UTF-8') ?></p>

        </blockquote>
      <?php endforeach; ?>
      
      
      <!--Delete joke -->
      <?php foreach($jokes as $joke): ?>
        <form action="?deletejoke" method="post">
            <blockquote>
                <p>
                    <?php echo htmltspecialchars($joke['text'], ENT_QUOTES, 'UTF-8'); ?>
                    <input type="hidden" name="id"  value="<?php echo $joke['id']; ?>">
                    <input type="submit" value="Delete">

                </p>
            </blockquote>

        </form>
      
      <?php endforeach; ?>
      
      
  </body>
</html>


Hi vancouver2990 welcome to the forum

What do you mean by “doesn’t work”?

eg. are there error messages, no error messages but the INSERT / DELETE / SELECT does something wrong or not doing something right?

This line seems a bit strange, in terms of passing an array into htmlspecialchars() - I couldn’t see anything quickly in the doc to suggest anything other than a string is suitable here.

 <p><?php echo htmlspecialchars($jAdd, ENT_QUOTES, 'UTF-8') ?></p>

But @mittineague is correct, we need to know more detail than “doesn’t work”.

Hi Mittineague ,
thank you for your answer, no there are no error messages, but the web browser is just blank without any jokes . Could you please tell me what i should do now?

hi droopsnoot ,
thank you for your answer , i just follow the guid of the book , that line is for encoding the jokes

If you look at view-source, there’s nothing there at all?

If you aren’t seeing any error messages displayed in any pages, there might still be some in the web developer tools console. I don’t remember if there is any JavaScript at this point in the book, but maybe?

AFAIK, most browsers open the console from 3 places, top menu “tools”, right-click “tools”, F12
(It might not be named tools exactly, but something similar. If your right-click context menu has an “inspect” that will open dev tools to the DOM, then switch to the console tab)

  • use your browser to go to the OK page - index.php
  • open dev tools console
  • perform action that goes to the broken page - submit form
  • keep an eye on the console for problems

Do you have error reporting enabled?
It’s a must for debugging.

2 Likes

im using the Google chrome and opened the source code from there , and here is what i got :

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Script output</title>
  </head>
  <body>
      
      <!--Add new joke -->
      <p><a href="?addjoke">Add your own joke</a></p>
      <p>Here are all the jokes in the database:</p>
              <blockquote>
            <p></p>

        </blockquote>
              <blockquote>
            <p></p>

        </blockquote>
              <blockquote>
            <p></p>

        </blockquote>
              <blockquote>
            <p></p>

        </blockquote>
              <blockquote>
            <p></p>

        </blockquote>
              <blockquote>
            <p></p>

        </blockquote>
              <blockquote>
            <p></p>

        </blockquote>
            
      
      <!--Delete joke -->
              <form action="?deletejoke" method="post">
            <blockquote>
                <p>
                    

is that the problem with this array?


while($row = $result->fetch()){
    $jokes[]= array('id' => $row['id'], 'text' => $row['joketext'] );
    
}
 

Because when i changed the code within the braces with this line:

$jokes[]= $row[joketext] ; 

then it worked and displayed all of the jokes in my database .

So i think there is a problem with array()?

how can i enable the error reporting function? :slight_smile:

As I said above, I think the problem is that you cannot pass the $jAdd array into htmlspecialchars(). You could go back to the original and change that line to read

<p><?php echo htmlspecialchars($jAdd['text'], ENT_QUOTES, 'UTF-8') ?></p>

so that you’re just passing in the joke text, not the id and text as an array.

ETA - surprised that the page source you showed results in a blank page in the browser. Doesn’t it display this bit?

 <p><a href="?addjoke">Add your own joke</a></p>
      <p>Here are all the jokes in the database:</p>

It is usually set in the php.ini file.

http://php.net/manual/en/language.errors.basics.php

Yes, the array is a multi-dimensional array eg.

array(3) 
 [0] => array(2) 
    [‘id’] => 1, 
    [‘text’] => ‘a horse walks into a bar’
 [2] => array(2) 
    [‘id’] => 2, 
    [‘text’] => ‘the pope, a rabbi, the president and an atheist’
 [3] => array(2) 
    [‘id’] => 3, 
    [‘text’] => ‘when is a string not a string’ 

So the code

   <?php foreach($jokes as $jAdd): ?>
        <blockquote>
            <p><?php echo htmlspecialchars($jAdd, ENT_QUOTES, 'UTF-8') ?></p>
        </blockquote>
      <?php endforeach; ?>

would be trying to echo an array. With PHP error reporting enabled you should see an error message something like “array to string”

If all you need is the text for that block of code I think this would work

   <?php foreach($jokes as $jAdd): ?>
        <blockquote>
            <p><?php echo htmlspecialchars($jAdd[‘text’], ENT_QUOTES, 'UTF-8') ?></p>
        </blockquote>
      <?php endforeach; ?>

im trying to get both id and joketext , so what should i change in this code?

while($row = $result->fetch()){
    $jokes[]= array('id' => $row['id'], 'text' => $row['joketext'] );
    
}

here is my code in jokes.html.php in oder to display the little box with delete function next to the joke text like in the tutorial book

<!--Delete joke -->
      <?php foreach($jokes as $joke): ?>
        <form action="?deletejoke" method="post">
            <blockquote>
                <p>
                    <?php echo htmltspecialchars($joke['text'], ENT_QUOTES, 'UTF-8'); ?>
                    <input type="hidden" name="id"  value="<?php echo $joke['id']; ?>">
                    <input type="submit" value="Delete">

                </p>
            </blockquote>

        </form>
      
      <?php endforeach; ?>

i also enabled the error_reporting on for all versions of php , but it didnt show anything :frowning:

yes it did display those text :slight_smile:

how can i pass the id and text as an array with htmlspecialchars?
thank you so much for your patience :slight_smile:

Ah, OK. You confused matters by saying you had a blank screen in the browser.

You can’t, as far as I know. Pass them in separately if you need to, but if the id field is an auto-incrementing numeric field in the database, is there any need to call htmlspecialchars() on it? In your code for the delete-jokes section, you don’t process the id there.

Also, typo:

<?php echo htmltspecialchars($joke['text'], ENT_QUOTES, 'UTF-8'); ?>

you can safely drop that whole section:

1 Like

thank you you guys so much :slight_smile:

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