1

我有一个快速的问题。我有代码返回论坛的单独标题的最后一篇文章。我想限制显示的字符数并放置(... ...)。

我的 while 循环中的嵌套 if 语句遇到了困难:

    $query  = "SELECT comment FROM Assembly WHERE title = 'Checkered' ORDER BY date DESC LIMIT 1";
$result = mysql_query($query);


while($row = mysql_fetch_assoc($message))
{

 if(strlen($message) > 10)
  {
   echo substr($message, 0, 10)."…";
  }
 else
  {
    echo    "Last Post:<br>";
    echo    strip_tags("{$row['comment']}");

  }
}

提前致谢 :)

**编辑是 css 文本溢出:省略号;效果很好!!多谢你们

***编辑工作代码以防万一

   $query  = "SELECT comment FROM Assembly WHERE title = 'Checkered' ORDER BY date DESC LIMIT 1";
$result = mysql_query($query);

while($row = mysql_fetch_assoc($result))
{

 $comment = strip_tags($row['comment']);
 if(strlen($comment) > 30)
  {
   echo substr($comment, 0, 30)."...";
  }
 else
  {
    echo    "Last Post:<br>";
    echo    $comment;

  }
}
4

2 回答 2

2

您的代码存在的问题是您有一些命名错误的变量。您分配mysql_query()to返回的结果资源$result,然后尝试从名为的变量$message中获取一行(您没有显示分配),然后切换到将$message其视为字符串,而不是在$row.

无论如何,如果您只想从数据库中获取字符串并应用省略号,并且不需要全文,我会让 MySQL 为我完成这项工作:

SELECT IF(CHAR_LENGTH(`comment`) > 10, CONCAT(SUBSTRING(`comment`, 1, 10), '...'), `comment`) AS `comment`
FROM `Assembly`
WHERE `title` = 'Checkered'
ORDER BY `date` DESC
LIMIT 1

在 PHP 中:

$query  = "
  SELECT IF(CHAR_LENGTH(`comment`) > 10, CONCAT(SUBSTRING(`comment`, 1, 10), '...'), `comment`) AS `comment`
  FROM `Assembly`
  WHERE `title` = 'Checkered'
  ORDER BY `date` DESC
  LIMIT 1
";
$result = mysql_query($query);

while ($row = mysql_fetch_assoc($result)) {
  echo    "Last Post:<br>";
  echo    htmlspecialchars($row['comment']);
}

编辑

在@Jared 对显示部分 HTML 标记的损坏字符串的可能性发表评论之后,以下是避免这种情况的方法:

$query  = "
  SELECT `comment`
  FROM `Assembly`
  WHERE `title` = 'Checkered'
  ORDER BY `date` DESC
  LIMIT 1
";
$result = mysql_query($query);
// Loop is pointless because of the LIMIT 1
$row = mysql_fetch_assoc($result);

$maxlen = 10; // Max length before trim
$comment = strip_tags($row['comment']);
if (strlen($comment) > $maxlen) {
  $comment = substr($comment, 0, $maxlen).'...';
}
$comment = htmlspecialchars($comment);

echo "Last Post:<br>";
echo $comment;
于 2012-06-30T18:59:49.623 回答
1

你放弃了这个问题,但我会冒险去猜测问题。试试这个:

while($row = mysql_fetch_assoc($message))
{

 $comment = strip_tags($row['comment']);
 if(strlen($coment) > 10)
  {
   echo substr($comment, 0, 10)."...";
  }
 else
  {
    echo    "Last Post:<br>";
    echo    $comment;

  }
}
于 2012-06-30T18:55:07.487 回答