Tutorial to limit the amount of characters from a MySQL query. You can limit the amount of characters that come out of a query quite easily with the function SUBSTRING().
For example say you were printing out news items but only wanted a short amount of text say 200 characters you would do this by issuing the command SUBSTRING(first charactor, last character) giving it the start position and the end position of text to bring out.
Lets do it in a working example:
This is a standard MySQL query first I add a variable to run the query then using mysql_query to actually run it then am telling MySQL to select everything (*) then issuing SUBSTRING(newsContent,1,200) as news from the newstable.
What were saying is get the newsContent but only characters from the first character to the 200th charactor including spaces then reference it as news. Get it from the newstable.<
Then run a die command the query fails
//query database and get first 200 characters
$result = mysql_query("SELECT * SUBSTRING(newsContent,1,200) as news FROM newstable")or die(mysql_error());
then create a while loop which will get all results and add them to the variable $row as an object using mysql_fetch_object(). Then we can call any object contained within the object using -> this is useful if you want to print out multiple columns from your database with a very simple query.
Then print out the news object by telling $row to get the inner object of news as defined by the query $row->news then close the loop.
//loop through all results and create the results into an object
while ($row = mysql_fetch_object($result)) {
// print out the news
echo $row->news;
//close the loop
}
The end result would print out all rows from the database but it would only print out the first 200 characters.
Here's the full script:
<?php
//query database and get first 200 characters
$result = mysql_query("SELECT * SUBSTRING(newsContent,1,200) as news FROM newstable")or die(mysql_error());
//loop through all results and create the results into an object
while ($row = mysql_fetch_object($result)) {
// print out the news
echo $row->news;
//close the loop
}
?>