0

I'm having troubles working something out. I have just used a threaded comment example online, tested it against manually inputted data and works perfectly.

enter image description here

But this setup is kind of strange. It uses a PATH method, so the first comment has a path of 01, a reply to that comment has a path of 01_01 and another reply to the first comment would have 01_02. You can see the relative paths in my screenshot (above), next to each name.

This method performs really well, as I have tested it against many, many comments. The problem I have is calculating the next reply path. For example, let's say my user clicks [reply] on Jeremy Clarkson's comment, which has a path of 01_01_01. The next sequence to this would be 01_01_02, but that has already been used by Kim Bauer's comment. I thought I could do a little query SELECT * FROM comments WHERE path LIKE '01_01_%' and select the last row and add 1 to it, but the comment from Chloe O'Brien has 01_01_01_01, which would affect this result.

Can somebody please explain how I can calculate the next correct path for a reply?

My Fix:

I calculate the next available path by doing this:

SELECT path
FROM blog_comments
WHERE path LIKE '01_01___'
ORDER BY path DESC
LIMIT 1

$last_path = $row[0];
$last_path_suffix = substr($last_path,strrpos($last_path,'_')+1);
$next_path_suffix = str_pad($last_path_suffix+1,2,'0',STR_PAD_LEFT);
$next_path = substr($last_path,0,strlen($last_path)-strlen($last_path_suffix)).$next_path_suffix;

If anybody would like to use this method, the printing goes something like this:

$SQL = "SELECT * FROM comments ORDER BY path ASC;";

while($row = $STH->fetch()) {
    $nesting_depth = strlen($row['path']) - strlen(str_replace('_','',$row['path']));
    $left_margin = $nesting_depth * 40; // 40 pixels nesting indent

    echo '<div class="comment_item" style="margin-left:'.$left_margin.'px;">';
        echo '<strong>'.htmlspecialchars($row['author_name']).'<br>';
        echo htmlspecialchars($row['comment']).'<br>';
    echo '</div>';
}
4

1 回答 1

1

You could search for exactly two digits using two underscores __. Underscore is a wildcard that matches exactly one unknown character. And you should escape the literal underscores since _ is a wildcard character.

SELECT * FROM comments WHERE path LIKE '01\_01\___' ESCAPE '\'
于 2012-10-20T17:26:48.933 回答