Jump to content

Can't figure out why HTML blocks won't change


TechnoDiver
 Share

Recommended Posts

Hi again, Freaks, hope you've all been well.  I have what I would have considered a simple problem if not for the trouble it's giving me.

I have the following bit ->

<?php if(!$message) : ?>
    <h4>Leave a comment</h4>
<?php else : ?>
    <div class='success'>
        <p class='bg-success text-center'>We have your comment and it will be added after approval</p>
    </div>
<?php endif; ?>

this code is obviously in the body of the page. At the top I have this ->

<?php 
require("assets/initializations.php");
$post_obj = new Post($conn, $user);

//simply increase #views per page load
if(isset($_GET['post_id']) && !empty($_GET['post_id'])) {
    $id = $_GET['post_id'];
    $query = mysqli_query($conn, "SELECT * FROM news WHERE id=$id");
    $row = mysqli_fetch_array($query);
    $category = $row['post_category'];
    $views = $row['num_views'];
    $views ++;
    mysqli_query($conn, "UPDATE news SET num_views='$views', time_stamp=NOW() WHERE id=$id");

    //comment to db
    $message = false;                   
    if(isset($_POST['submit'])) {
        mysqli_report(MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT);
        $comment_obj = new Comment($conn);

        if($comment_obj->addComment($id, $_POST['name'], $_POST['email'], $_POST['comment'])) {
            $message = true;
        }    
    }
}
?>

Everything works fine except I can't get the body if statement to show anything other "Leave a Comment". The comment gets to the database but the success message won't show.

I've tried this various ways before using this format. I assigned the $message up top and tried echoing it in the body. I then tried ternary style. Then I remembered that I had to do the same thing months ago when I made the registration form. So I decided to try that style here. The code from the register.php is this ->

<?php if(!empty($errors)) : ?>
  <div class="errors">
    <p class="bg-danger text-center"><?php echo implode( '</p><p class="bg-danger text-center">', $errors ); ?></p>
  </div>

<?php elseif($sent) : $js_switch = true; ?>
  <div class="success">
    <p class="bg-success">You've been successfully registered. Login and enjoy the network.</p>
  </div>
<?php endif; ?>

This code works great and is why I decided to do the same on my current issue, but nothing that I do gets "Leave a Comment" to change to the success message.

Is there some obscure rule of PHP I've overlooked? I really can't figure out why the bit I'm working on now isn't working correctly like that bit I copied it from.

Thanks for all responses

Link to comment
Share on other sites

Posted (edited)
1 hour ago, kicken said:

Have you verified if $comment_obj->addComment is returning a true value so that your $message = true; line will be executed?

yea yea, it sends all data to the database. It's only this one part that's not working.

If you tell me that it can send the date to the database and still return false I'll have to reevaluate everything I thought I understood about PHP lol

Here's the addComment method if it helps

public function addComment($id, $name, $email, $body) {
  if(!empty($body) && !empty($email)){

      $name = strip_tags(mysqli_real_escape_string($this->conn, $name));
      $email = strip_tags(mysqli_real_escape_string($this->conn, $email));
      $body = nl2br(mysqli_real_escape_string($this->conn, $body));

      $statement = $this->conn->prepare("INSERT INTO comments (
          post_id, username, email, body
          ) VALUES (?,?,?,?)");

      $statement->bind_param('isss', $id, $name, $email, $body);

      if($statement) {
          $statement->execute();
      }
  }

 

Edited by TechnoDiver
Link to comment
Share on other sites

33 minutes ago, TechnoDiver said:

If you tell me that it can send the date to the database and still return false I'll have to reevaluate everything I thought I understood about PHP lol

Time to re-evaluate then.

Your function doesn't return anything.  In that case, trying to capture a return value results in NULL which when used in an if statement equates to false.

If you want to return a value from a function, you need to do so explicitly with the return keyword.  So you need to either modify your function to return true or false appropriately or just remove your if statement where you call the function.

 

  • Like 1
Link to comment
Share on other sites

Posted (edited)

I"ve resolved this. The solution was changing

if($statement) {
    $statement->execute();
}

to

if($statement) {
    $statement->execute();
    return true;
}

So the issue has been resolved but I don't quite understand why the top statement doesn't return true by default

 

EDIT: Thanks Kicken, I saw the notification for you comment as I was typing my resolution. I appreciate your effort anyways

You also helped me understand why the 'return true;' line isn't redundant like it seemed.

Edited by TechnoDiver
Link to comment
Share on other sites

12 minutes ago, TechnoDiver said:
$statement->execute();

an ->execute() call can fail due to something wrong with the data being supplied to the query. what's your error handling for that case?

i also see you edited a post above to add the code for the addComment method. you are using a prepared query. do NOT also use mysqli_real_escape_string on the data. this will result in the actual escape characters \ being inserted into the database, which will prevent searches from matching data. the main point of using a prepared query is to protect against sql special characters from breaking the sql query syntax, for all data types, not just strings. i also see you are applying nl2br to the input data. this is an OUTPUT function. it is used when you output data in a html context. do NOT use it on input data being stored in a database.

  • Like 1
Link to comment
Share on other sites

Posted (edited)
32 minutes ago, mac_gyver said:

an ->execute() call can fail due to something wrong with the data being supplied to the query. what's your error handling for that case?

Not done yet, but aware that it needs to be. I'm still in that linear way of thinking that pieces together as I go and trying to get to a broader cyclical way of seeing an app.

Thanks for commenting. I must have misunderstood my read-up on nl2br(). I also did not know that about mysqli_real_escape_string().

What are normally the proper 'sanitizing' functions to use before sending text data TO a database?

Edited by TechnoDiver
Link to comment
Share on other sites

2 hours ago, TechnoDiver said:

What are normally the proper 'sanitizing' functions to use before sending text data TO a database?

When storing data, you just need to ensure you don't fall victim to SQL Injection.  Using bound parameters rather than inserting values directly into your SQL takes care of that, so there's no need for things like mysqli_real_escape_string.

In addition, you shouldn't be modifying your input with things like nl2br to htmlspecialchars etc.  Do that kind of manipulation at the time you output the data, not when it's received.  If you modify it before you store it, you open yourself up to future problems such as if you decide tomorrow you want to output that data to a PDF file rather than HTML, or save it in a CSV file or include it in an image, etc.  If you store the data with the HTML specific manipulations then you'll have to find some way to undo all those manipulations before using the data in another context.

 

Link to comment
Share on other sites

I usually "clean" user input before adding to the database.

the retrieved $_REQUEST['input...'] => I replace all

quotes ' with ’  (right single quotation)

and double quotes " by ” (right double quotation)

when inserting right single or double quotation marks, it fits without the need of escaping....

Link to comment
Share on other sites

Yea, that all makes sense. And yea sometimes things don't stick the first time depending on my state of mind when hearing it and learning a lot at once. I often have to come back here to look into old questions I asked that I only have a vague memory of asking about the first time.

Thank you, all

Would any of you fine freaks have suggestions or some good links where I can start researching how to allow users to use markup and/or HTML in their submissions

and how to handle all that going to and from the database?

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.