tehX
tehX

Reputation: 167

Querying only 400 characters from the database won't work

I have this line of code:

$query=$db->prepare("SELECT post_id, title, LEFT(body, 400), category FROM posts INNER JOIN categories ON categories.category_id=posts.category_id ORDER BY post_id DESC LIMIT $start, $per_page");

The LEFT(body,400) won't query 400 characters only, it will query all but the last word. This is the code I use to echo the query (its in a while loop w/ db)

<p><?php
     $body_sub = substr($body, 0). "...<a href='post.php?id=$post_id'> Continue Reading →</a>";
    echo nl2br($body_sub);
?></p>

Upvotes: 1

Views: 59

Answers (1)

Kermit
Kermit

Reputation: 34063

The column body does not technically exist after you use it in a function. You need to alias the column:

... LEFT(body, 400) AS body

Then call body.

I would also recommend using backticks around system terms such as columns:

SELECT `post_id`, 
       `title`, 
       LEFT(`body`, 400) AS `body`, 
       `category`
FROM   `posts`
       INNER JOIN `categories` 
               ON `categories`.`category_id` = `posts`.`category_id` 
ORDER  BY `post_id` DESC 
LIMIT  $start, $per_page

Upvotes: 3

Related Questions