You can select the whole post
and title
and truncate that in PHP
SQL
SELECT post, title
FROM news WHERE title LIKE '%$searchfor%'
ORDER BY item_id DESC
LIMIT 20
PHP
function limit_words($words, $limit, $append = ' …') {
$limit = $limit+1;
$words = explode(' ', $words, $limit);
array_pop($words);
$words = implode(' ', $words) . $append;
return $words;
}
// this actually will give you 100 words
echo limit_words($result->post, 100);
// this will give you 100 characters
echo substr($result->post, 0, 100);
There is one more way to do it straight in the SQL that might save some memory.
SQL
SELECT SUBSTRING(post, 0, 100) AS post, title
FROM news WHERE title LIKE '%$searchfor%'
ORDER BY item_id DESC
LIMIT 20
If you want to search both the title
and the post
fields you'll need to add them to the WHERE clause:
SQL
SELECT post, title
FROM news
WHERE title LIKE '%searchfor%' AND post LIKE '%searchfor%'
ORDER BY item_id DESC
LIMIT 20
### If you need to map search term in either post OR title ###
SELECT post, title
FROM news
WHERE title LIKE '%searchfor%' OR post LIKE '%searchfor%'
ORDER BY item_id DESC
LIMIT 20