I’m escaping blog posts with sqlite_escape_string(), and connecting to the database using the old object-oriented way.
(Yes, I know, I should use PDO, I’ll get to that later; converting this script would take quite a while.)
When I have data like: It's raining cats and dogs!, it saves this to the database: It''s raining cats and dogs!. The problem is that it comes out of the database like that, and stripslashes() doesn’t undo it. Magic Quotes is turned off.
Every time I recall that data from the database and save it again, it adds more single-quotes. How would I stop it from doing that?
Here’s the abridged submission code:
# Grab the data from form and escape the text
$title = sqlite_escape_string(strip_tags($_POST['title']));
$text = sqlite_escape_string($_POST['text']);
# Query for previous data
$result = @$dbh->query("SELECT * FROM posts WHERE id=".$id);
# Fetch previous data
while($past = $result->fetchObject()) {
$ptitle = $past->title;
$ptext = $past->post;
}
# Set a base query to modify
$base = "UPDATE posts SET ";
# Run through scenarios
if(stripslashes($ptitle) !== $title) { $base .= "title='".sqlite_escape_string($title)."', "; }
if(stripslashes($ptext) !== $text) { $base .= "text='".sqlite_escape_string($text)."', "; }
}
# Remove last comma & space
$base = substr($base, 0, -2);
$base .= " WHERE id=".(int)$id;
# Execute modified query
@$dbh->query($base);
And here’s the code that reads the data back:
# Sanitize and set variables
$start = (int)$start;
$limit = (int)$limit;
$start = ($start - 1) * $limit;
$dbh = $this->dbh;
$this->limit = $limit;
# Query the database for post data
$this->result = $dbh->query("SELECT * FROM posts ORDER BY id desc LIMIT ".$start.", ".$limit);
public function loop() {
# Do we have any posts?
if(!empty($this->result)) {
# Convert query results into something usable
$this->cur_result = $this->result->fetchObject();
# This while loop will remain true until we run out of posts
while($post = $this->cur_result) {
return true;
}
# At which point it turns false, ending the loop in the template file
return false;
}
# We don't have any posts :(
else {
return false;
}
}
public function content($excerpt = '') {
# We didn't screw up and keep an empty query, did we?
if(!empty($this->cur_result)) {
echo stripslashes($this->cur_result->post);
}
}
It looks like you are escaping the data twice.
At the beginning of your code you have:
And then in the insert you have:
Remove the sqlite_escape_string from the if statements and I think the result will come out correctly now.