r/PHPhelp • • Aug 07 '25

Backslashes viewable with php echo

I promise i have read around prior to posting but I i just don't get how to make this work. I've tried reading and experimenting with htmlspecialchars, htmlentities,and mysql_real_escape_string but its not going in and can't figure out to get things "human legible" (i.e. no ampersand and apos or \' )

<?php
/*----------------------- FORM PROCESSING Update casualty details-------------------*/
//Check if the update was submitted
if (isset($_POST['notesupdate'])) {

    $notes = $_POST["notes"];
    try {
        $statement = $conn->prepare("UPDATE tbl_notes
                    SET 
                  tbl_notes.note = :note
                  WHERE
                  note_id=:note_id");

        $statement->execute([
            'note_id' => $note_id,
            'note' => $notes
        ]);
        
          echo "<script>window.location = window.location</script>";
        
    } catch (PDOException $e) {
        echo "Database Error: Could not update the notes.<br>" . $e->getMessage();
        exit();
    } catch (Exception $e) {
        echo "General Error: Could not update the notes.<br>" . $e->getMessage();
        exit();
    }
}
/*------------ END FORM ----------------*/
?>

<div class="card-header">
    <form action="" method="post" id="">
       <strong>Notes</strong>
    </div>
    <div class="card-body">
        <div class="row">
            <div class="col-sm px-md-5" >
                <textarea id="notes" name="notes" rows="40" cols="50">
                <?php echo htmlspecialchars($cas_notes); ?></textarea>   
               <input type="submit" name="notesupdate" value="Save" class="btn btn-success">
                </form> 
        </div>
    </div>
</div>

I have the LONGTEXT field to store the notes in the database. Each time I submit anything with ' or " it is converted and stored in the database as \' or &apos; depending on the method used.

Ideally I'd like to be able to store this information "safely" and subsequently return it to the user legibly. I'm not sure why it is different on this field but it isn't playing nice.

Thanks

DAn

1 Upvotes

35 comments sorted by

View all comments

Show parent comment

1

u/danlindley Aug 07 '25

Gone are the days of the 90's when it was all simple html!

In my head tag i have, not sure what the database definition is however phpmyadmin reports each table as utf8mb4

 <meta charset="utf-8">

Can you help walk me through some of the points you raised please?

- setting the charset at the connection
- what's the difference between a real and emulated prepared query? how do i covert to the former?

I'm helping a friend out with a project and have inherited the code i'm working from as well as learning as I go and theres a lot of evolutionary changes

1

u/equilni Aug 07 '25

Here is what you want:

https://phpdelusions.net/pdo#dsn

Charset is part of the dsn and PDO::ATTR_EMULATE_PREPARES is part of the options or setattribute