Skip to content
Advertisement

How can I alternate between mysqli_real_escape_string and nl?

I’ve been doing some reading on mysqli_real_escape_string(), and, after getting my content properly escaped, I’m having some trouble getting to display properly when I pull it out again.

Here’s the code I have:

function update_section_content() {
    $name = mysqli_real_escape_string($this->conn, $_POST['name']);
    $text = mysqli_real_escape_string($this->conn, $_POST['content']);

    // First, we do an update
    $update_query = "UPDATE sections SET content = ? WHERE name = ?";
    if($update_stmt = $this->conn->prepare($update_query)) {
        $update_stmt->bind_param('ss', $text, $name);
        $update_stmt->execute();
        // If the update was successful, read in what we just updated
        if($update_stmt->affected_rows == 1) {
            $read_query = "SELECT content FROM sections WHERE name = ?";
            if($read_stmt = $this->conn->prepare($read_query)) {
                $read_stmt->bind_param('s', $name);
                    $read_stmt->execute();
                $read_stmt->bind_result($content);
                if($read_stmt->fetch()) {
                    echo nl2br($content);
                }
            }
        }
        $read_stmt->close();
        $update_stmt->close();
}

My hope for the following code was that it would update a record and escape any bad characters, and then, upon success, read the updated query back while maintaining its previous visual integrity. (That is, I’d like for the textarea this content gets echoed into to display newlines and not br tags.)

Unfortunately, as of now, I’m still getting newline characters shown after escaping. What am I missing?

Much thanks for your time, and any advice provided is greatly appreciated.

Unfortunately, that’s not the case. I still get newline characters

Advertisement

Answer

Since you’re using prepared statements, you shouldn’t also escape your strings.

String escaping is for when you’re embedding the values into the SQL query string itself, but by using prepared statements, you’re quite rightly avoiding doing that.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement