Domanda

I have this query to make a quick search on my database

$result = $apt->query("SELECT * FROM news where title like '%$searchfor%' order by item_id DESC limit 20");

I would like to include the first 100 character of "post" row in this search query as well as the title row. Sometimes I have some characters that people may search for are available within the first 100 character of "post" row.

Any Idea? Thanks

È stato utile?

Soluzione

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top