I have a mySQL table named businesses with 4 columns.
name, url, description, category
I am trying to have the entire directory display on a page under each corresponding category name. Is there a better way to do this than what I have so far? I would like to keep all data in one table rather than having a table for each category.
<?php
$con = mysql_connect('localhost','username','password')
or die('Could not connect: ' . mysql_error());
mysql_select_db('relicc_dogedir')
or die('Could not select database');
$result = mysql_query("SELECT * FROM businesses ORDER BY category",$con);
$column = array();
while($row = mysql_fetch_array($result))
{
$column[] = $row['category'];
}
$merged_column = array_unique($column);
$refined_categories = array_values($merged_column);
foreach ($refined_categories as &$refined_category)
{ ?>
<h3><?php echo $refined_category;?></h3><?php
//Display sorted business names with corresponding category
}
mysql_close($con);
?>
First, you should know that the mysql extension is deprecated, you should use MySQLi or PDO_MySQL.
You could first retrieve the categories, and then foreach categories retrieve the corresponding businesses.
try
{
$dbh = new PDO('mysql:host=localhost;dbname=YOURDB', 'USERNAME', 'PASSWORD');
}
catch(PDOException $e)
{
echo $e->getMessage();
die;
}
$stmt = $dbh->query('SELECT category FROM businesses GROUP BY category');
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$categories = $stmt->fetchAll();
foreach ($categories as $category)
{
echo '<h3>'.$category['category'].'</h3>';
$stmt = $dbh->prepare('SELECT * FROM businesses WHERE category = :categoryName');
$stmt->bindParam(':categoryName', $category['category'], PDO::PARAM_STR);
$stmt->execute();
$businesses = $stmt->fetchAll();
foreach ($businesses as $business)
{
echo $business['name'];
echo '<br />';
}
}
You could group your data by category
in PHP.
...
$result = mysql_query("SELECT * FROM businesses ORDER BY category, name", $con);
$data = array();
while($row = mysql_fetch_array($result))
{
$data[$row['category']][] = $row;
}
foreach($data as $categoryName => $categoryData) {
echo '<h3>' . $categoryName . '</h3>';
foreach ($categoryData as $business) {
// display sorted business data using business
// echo $business['name'];
}
}
...