View Full Version : Search a database and display results in a table

08-07-2006, 03:55 AM
I have a script that searches my database and displays the results, but does not display it in a table. I would like the table to be 4 columns, and the rows to continue until however many items there are.

Here is the script (thanks if you can help!):

$db_host = "localhost";
$db_user = "username";
$db_pass = "password";
$db_name = "databasename";
$dbac = mysql_connect($db_host,$db_user,$db_pass);
mysql_select_db ($db_name) or die ("Cannot connect to database.");

if (!$_POST['search']){
<form name="Item Search" method="post" action="">
Item Search:<br>
<input name="swords" type="text" size="30" maxlength="30">
<input name="search" type="submit" id="search" value="Search">
$searchwords = addslashes(htmlspecialchars($_POST['swords']));
if (strlen($searchwords) < 2){
echo "Your search must contain at least 3 characters. Please try again.<br><input type=button value='Back' onClick='history.go(-1)'>";
$words = explode(' ',$searchwords);
$totalwords = count($words);
$i = 0;
$searchstring = "";
while ($i != $totalwords){
if ($i != 0 and $i != $wordcount){
$searchstring .= " and ";;
$searchstring .= "name LIKE '%$words[$i]%'";
$i = $i + 1;
$query = mysql_query("SELECT DISTINCT * FROM items where $searchstring");
if (mysql_num_rows($query) == 0){
echo "No results were found.<br><input type=button value='Back' onClick='history.go(-1)'>";
while ($row = mysql_fetch_array($query)){
echo '<table>';
echo '<tr>';
echo '<td>'.$row['name'].'</td>';
echo '<td><img src="'.$row['imgurl'].'"></td>';
echo '<td>'.$row['category'].'</td>';
// etc
echo '</tr>';
echo '</table>';

08-07-2006, 04:13 AM
your echo "<table>" and echo "</table>" need to be outside your while loop, else you are putting each row in a separate table