I’m trying to build a Vendor Contact Database with categories. Various vendors are marked under more than one category. I have structured my table as the following:
Name_Vendor | Category_1 | Category_2 | Category_3 | John Smith | 1 | 0 | 1 | Plumber Jim | 0 | 0 | 1 |
My Current Code
$category_Title_1 = "Appliance Repair"; $category_1 = "Category_1"; $category_Title_2 = "Handyman"; $category_2 = "Category_2"; $category_Title_3 = "Plumber"; $category_3 = "Category_3"; $result = mysqli_query($conn,"SELECT * FROM `vendors` WHERE ".$category_1 ."='1'ORDER BY Name_Vendor ASC"); $row_cnt = $result->num_rows; if ($row_cnt == 0 ){echo "<div>";} else { echo "<div>".$category_Title_1."</div>"; while($row = mysqli_fetch_array($result)) { echo $row['Name_Vendor']; echo "</div>";} $result = mysqli_query($conn,"SELECT * FROM `vendors` WHERE ".$category_2 ."='1'ORDER BY Name_Vendor ASC"); $row_cnt = $result->num_rows; if ($row_cnt == 0 ){echo "<div>";} else { echo "<div>".$category_Title_2."</div>"; while($row = mysqli_fetch_array($result)) { echo $row['Name_Vendor']; echo "</div>";} $result = mysqli_query($conn,"SELECT * FROM `vendors` WHERE ".$category_3 ."='1'ORDER BY Name_Vendor ASC"); $row_cnt = $result->num_rows; if ($row_cnt == 0 ){echo "<div>";} else { echo "<div>".$category_Title_3."</div>"; while($row = mysqli_fetch_array($result)) { echo $row['Name_Vendor']; echo "</div>";}
This is just a basic idea. My contact database has more fields including phone number, email, etc.
Seeing how our category numbers have grown to a large amount, I’m looking for a way to not have to copy the same code multiple times within the same page in order to display all the categories.
Advertisement
Answer
$keyValuePairArray = { 'key1' => 'value1', 'key2' => 'value2', ... }; foreach($keyValuePairArray as $key=>$value){ //do whatever it is that you're doing //repetitively in your code above //if you don't understand this try using var_dump on your array //and echo out the $key and $value so that you might better understand //or research about all the items I have mentioned previously }