我遇到一个问题,我无法选择每个帖子的前500个字符。 (帖子存储在MySQL数据库中)。我现在拥有的代码是:

$link = mysqli_connect( 'localhost', 'jfairbanks_dbuser', 'password' );
mysqli_select_db( $link, 'jfairbanks_database' );
$results = mysqli_query( $link, "SELECT post FROM Users where verified = 1 LIMIT 0 , 10" ); //this displayes all the posts that have been verified
while( $record = mysqli_fetch_assoc( $results ) ) {
 $post = $record['post'];
 print $post;
}
  mysqli_free_result( $results );
mysqli_close( $link );
?>


该代码从所有经过验证的帖子中选择所有字符,这很好,但是我需要限制所显示帖子的长度。 (我只希望看到前500个字符)。

我尝试使用LEFT(post, 500)进行其他操作,但这没有用。

最佳答案

正如我在评论中提到的那样,在MySQL中使用LEFT()函数后,需要为您的字段提供别名。

您的查询如下所示:SELECT LEFT(post,500) AS post FROM Users ...

通过使用post作为别名,您现在可以像以前一样在关联数组中访问它:

$post = $record['post'];

在sql查询中没有别名的情况下,数组没有键post,并引发您收到的异常。

关于php - 仅返回文本的前500个字符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41030385/

10-12 12:33
查看更多