以下是我显示用户评论的查询。效果很好:
enter
$query='SELECT
customers.cust_id,
customers.f_name,
customers.l_name,
user_comments.comment_txt,
clubs.name_club
from
customers
inner join
user_comments
on customers.cust_id = user_comments.cust_id
inner join
clubs
on user_comments.cust_id = clubs.cust_id
ORDER BY RAND() LIMIT 1,1
';
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
$nameclub =$row['name_club'];
$comment =$row['comment_txt'];
echo '<div><img src="images/arrow.gif"> <a href="news.php?id='.$row['cust_id'].'"> Name : '.$nameclub.'</a></div>';
echo '<div>'.$comment.'</div><br>';
echo '<div>'.$row['f_name'].' '.$row['l_name'].'</div>';
}
echo '<p style="text-align: left"><a href="newsarchive.php"> Show all comments</ ></a></p> '; ?>
我现在想要显示用户评论的大约100个字符。所以我相应地更改了我的查询,但它不起作用:
enter $query='SELECT
customers.cust_id,
customers.f_name,
customers.l_name,
user_comments.comment_txt.substr(comment_txt,1,100) as comment_txt,
clubs.name_club
from
customers
inner join
user_comments
on customers.cust_id = user_comments.cust_id
inner join
clubs
on user_comments.cust_id = clubs.cust_id
ORDER BY RAND() LIMIT 1,1
';
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
$nameclub =$row['name_club'];
$comment =$row['comment_txt'];
echo '<div><img src="images/arrow.gif"> <a href="news.php?id='.$row['cust_id'].'"> Name : '.$nameclub.'</a></div>';
echo '<div>'.$comment.'</div><br>';
echo '<div>'.$row['f_name'].' '.$row['l_name'].'</div>';
}
echo '<p style="text-align: left"><a href="newsarchive.php"> Show all comments</ ></a></p> '; ?>
如何修复查询以获得评论的100个字符?
答案 0 :(得分:5)
您未正确使用SUBSTR()
。替换这个:
user_comments.comment_txt.substr(comment_txt,1,100) as comment_txt,
有了这个:
SUBSTR(user_comments.comment_txt,1,100) as comment_txt,
修改每条评论:如果文字继续超过100个字符,则添加...
,请使用
CONCAT(SUBSTR(user_comments.comment_txt,1,100), IF(LEN(user_comments.comment_txt) > 100, '...', '')) as comment_txt,
答案 1 :(得分:0)
试试这个
替换此
user_comments.comment_txt.substr(comment_txt,1,100) as comment_txt,
要
SUBSTRING(user_comments.comment_txt,1,100) as comment_txt,
答案 2 :(得分:0)
另一个解决方案是使用php函数将字符串剪切成多个单词:
<?php
function cut_string($string_to_cut, $number_words, $append = "...") {
$string = array();
$string_return = "";
$return_string = "";
$string = explode(" ", $string_to_cut);
if(count($string) < $number_words) {
for($x=0; $x < count($string); $x++) {
$string_return .= $string[$x] . " ";
}
$return_string = substr($string_return, 0, -1);
}
else {
for($x=0; $x < $number_words; $x++) {
$string_return .= $string[$x] . " ";
}
$string = substr($string_return, 0, -1);
$return_string = $string . $append;
}
return($return_string);
}
?>
注意:这是基于字数的,而不是基于字符数的。