Log in

View Full Version : Limiting Result Characters



Titan85
03-02-2007, 04:05 AM
Hello, I would like to know if there is a way to take only a specified amount of characters out of a mysql database. For example, I want to take the description of a job, but not the full description that is in the database, but say 100 characters of that description. How could I accomplish this? Thanks

thetestingsite
03-02-2007, 04:39 AM
With the use of substr(); (http://www.php.net/substr). An example would be as follows:



while ($row = mysql_fetch_row($result)) {
echo "<b><font face='Georgia, Times New Roman, Times, serif' size='-1'><a href='support_faq_view.php?faq_id=$row[0]'>$row[1]</a></font></b><br>";
echo "<font face='Georgia, Times New Roman, Times, serif' size='-2'>" . substr($row[5], 0, 50) . "..." . "</font>";
echo "<br><br>";
}


Hope this helps.

codeexploiter
03-02-2007, 05:10 AM
Actually most of the database package supports database specific functions like Left(), right() or Substr() using which you can extract the needed amount of field values from the table(s).

The solution thetestingsite proposed is based on the script language that means you are retrieving the whole amount of data but showing only the necessary items in your result.

If you use an SQL statement based on a database specific function on it it will return only the necessary data instead of returning the whole bunch of data especially if you are dealing with database fields that contains large volume of data like lengthy text data.

As an example consider the following SQL statement I've used MySQL db


SELECT LEFT(tablename.fieldName, 50) from tablename;
This will return the first 50 characters from the left side of the specified field. Please make sure that your table field is based on Text while using these kind of functions (left, right, susbtr, etc).


SELECT RIGHT(tablename.fieldName, 50) from tablename;
Returns the rightmost 50 characters from the table field specified in the statement.



SUBSTRING(str,pos,len)
MID(str,pos,len)

The above MySQL functions will give you characters from any location from a database field.

For more details you can refer your database package manual.

If nothing goes you can still achieve what you want using your server side scripting as thetestingsite stated.

Titan85
03-04-2007, 04:28 AM
The substr() is exactly what I was looking for, thanks a lot :)