Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do you limit the amount of characters shown in a table?

Coding

How do you limit the amount of characters shown in a table?

by  FAM  Posted    (Edited  )
When pulling data from a mysql table you may want to limit the amount of characters shown within a column to control the size of the table.

This basic script connects to a mysql database, pulls 4 columns of data into a html table and using the [link http://uk.php.net/substr]substr[/link] function, it limits 'Column 2' to 30 characters and also appending '...' to the 30th character.

Code:
<?php
$host="localhost";
$user="root";
$pass="";
$database="databasename";

$sConn = mysql_connect($host, $user, $pass) or die("Couldn't connect to database server");
$dConn = mysql_select_db($database, $sConn)or die("Couldn't connect to database $database");

echo '<table border="1" width="100%"><tr align="center"><td>Column 1</td><td>Column 2</td><td>Column 3</td><td>Column 4</td></tr>';

$CharacterLimit=30; 	// Define how many characters to be displayed

$sql = "SELECT * FROM tablename";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
	echo "<tr>\n";
	echo "<td width='25%'>".$row['Column1']."</td>\n";
	
	$Column2 = $row['Column2'];
	$ColumnLimit = substr($Column2, 0, $CharacterLimit);
	echo "<td width='25%'>".$ColumnLimit."...</td>\n";
	echo "<td width='25%'>".$row['Column3']."</td>\n";
	echo "<td width='25%'>".$row['Column4']."</td>\n";
	echo "</tr>\n";
}
echo "</table>";
?>
To go more in-depth you could could count the characters of 'Column 2' and if the result was less than 30, you would not need to append the '...'!

Hope this is of some use.
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top