PHP: Replace ID with string, based on decoded JSON number - php

The custom Wordpress plugin I installed, responsible for all kind of hotel booking requests, displays a calendar containing the for- and surname of our clients in the Wordpress backend. At first I didn't get the ID of the booked apartment, but now I got that which leads me to the next problem.
Unfortunately only the ID of the booked apartment is displayed in the backend. Is there a way to convert the ID into a predefined string before the page is displayed?
Like 237 ยป Apartment 4?
I already tried it with a If-condition, but nothings happened.
if ( !empty($booked_ids) ) {
foreach( $booked_ids as $key => $val) {
echo '<tr class="sh_booking_data">';
$booking_meta = get_post_meta( $val, '_booking_meta', true );
$arr = json_decode($booking_meta["save_rooms"], true);
die($arr["Room 1"]["room_type"]);
if ( $arr["Room 1"]["room_type"] == 237 ) {
$bodytag = "Apartment 4";
echo("<script>console.log('PHP: " . $arr["Room 1"]["room_type"] . "');</script>");
}
echo '<td>#' . $val . ' ' . $booking_meta["first_name"] . ' ' . $booking_meta["last_name"] . ' ' . $arr["Room 1"]["room_type"] . '</td>';
foreach( $month_1_2_array as $key => $val) {
if ( !empty($booking_meta["booking_status"]) ) {
if ( $booking_meta["booking_status"] == 1 ) {
$booking_status_class = 'pending';
} elseif ( $booking_meta["booking_status"] == 2 ) {
$booking_status_class = 'confirmed';
} elseif ( $booking_meta["booking_status"] == 3 ) {
$booking_status_class = 'cancelled';
} else {
$booking_status_class = 'unknown';
}
} else {
$booking_status_class = 'unknown';
}
if( $booking_meta["check_in"] == $val ) {
echo '<td class="sh_first_day_' . $booking_status_class . '"> </td>';
} elseif( $booking_meta["check_out"] == $val ) {
echo '<td class="sh_last_day_' . $booking_status_class . '"> </td>';
} elseif ( sh_get_date_range_overlap($val,$val,$booking_meta["check_in"],$booking_meta["check_out"]) == true ) {
echo '<td class="sh_booking_' . $booking_status_class . '"> </td>';
} else {
echo '<td> </td>';
}
}
echo '</tr>';
}
}
I'm very new to PHP and thanks in advance!

If you got multiple IDs, then you can list all the available IDs in if-else block and assign the relevant Apartment name for the relevant ID to the $bodytag, so you can use $bodytag to print echo it.
So below is an example:
Assuming that you have 6 ID's which are 237, 27, 251, 252, 255, and 260, so you put all of them in if-else block like this and assign the relevant apartment name for the relevant ID.
$bodytag = ""; // initialize the variable
if ($arr["Room 1"]["room_type"] == 237) {
$bodytag = "Apartment 4";
}
else if ($arr["Room 1"]["room_type"] == 27) {
$bodytag = "Apartment 10";
}
else if ($arr["Room 1"]["room_type"] == 251) {
$bodytag = "Apartment 12";
}
else if ($arr["Room 1"]["room_type"] == 252) {
$bodytag = "Apartment 13";
}
else if ($arr["Room 1"]["room_type"] == 255) {
$bodytag = "Apartment 15";
}
else{
$bodytag = "Apartment 20";
}
echo '<td>#' . $val . ' ' . $booking_meta["first_name"] . ' ' . $booking_meta["last_name"] . ' ' . $bodytag . '</td>';

Related

Show selected in multiple selection in PHP loop

I am listing multiple categories.
<?php
function listCategory($id = 0, $string = 0, $catID = 0){
global $sib;
$query = $sib -> prepare( "select * from categories where subCatID=? and isActive=? order by toSort asc" );
$query -> execute( array($id, 1) );
$view = $query -> fetchAll( PDO::FETCH_ASSOC );
$xe = $querye -> rowCount();
if ( $xe ) {
foreach ($view as $row) {
if ( $row["subCatID"] == 0 ) {
echo '<optgroup label="' . $row["title"] . '">';
} else {
echo '<option value="' . $row["categoryID"] . '" >';
}
echo str_repeat( " - ", $string ) . $row["title"];
listCategory( $row["categoryID"], $string + 1, $catID );
if ( $row["subCatID"] == 0 ) {
echo '</optgroup>';
} else {
echo '</option>';
}
}
} else { return false; }
}
listCategory( 0, 0, 0 );
?>
There is no problem with listing. Array contains category ID numbers.
$catIDs = array(4,7,18);
The categories whose id numbers are listed must be selected that are equal to their id number.
I've made a few attempts at this. I could not be successful.
I've made a few attempts at this. I could not be successful.
I solved the problem.
echo '<option value="' . $row["categoryID"] . '" >';
I edited this field
$catListA = array(4,7,18);
$selected = in_array($row["categoryID"],$catListA ) ? "selected" : "";
echo '<option value="' . $row["categoryID"] . '" '. $selected .'>';

I have some problem with send and write array in database (Codeingniter 3)

I have a form that sends customer data to the database, I added a choice of another category of customers through the input, and instead of sending the data in text, a number is sent.
db
In View
<?php echo render_select('sellers',get_sellers(),array('articleid','subject'),''); ?>
echo render_select helper:
function render_select($name, $options, $option_attrs = [], $label = '', $selected = '', $select_attrs = [], $form_group_attr = [], $form_group_class = '', $select_class = '', $include_blank = true)
{
$callback_translate = '';
if (isset($options['callback_translate'])) {
$callback_translate = $options['callback_translate'];
unset($options['callback_translate']);
}
$select = '';
$_form_group_attr = '';
$_select_attrs = '';
if (!isset($select_attrs['data-width'])) {
$select_attrs['data-width'] = '100%';
}
if (!isset($select_attrs['data-none-selected-text'])) {
$select_attrs['data-none-selected-text'] = _l('dropdown_non_selected_tex');
}
foreach ($select_attrs as $key => $val) {
// tooltips
if ($key == 'title') {
$val = _l($val);
}
$_select_attrs .= $key . '=' . '"' . $val . '" ';
}
$_select_attrs = rtrim($_select_attrs);
$form_group_attr['app-field-wrapper'] = $name;
foreach ($form_group_attr as $key => $val) {
// tooltips
if ($key == 'title') {
$val = _l($val);
}
$_form_group_attr .= $key . '=' . '"' . $val . '" ';
}
$_form_group_attr = rtrim($_form_group_attr);
if (!empty($select_class)) {
$select_class = ' ' . $select_class;
}
if (!empty($form_group_class)) {
$form_group_class = ' ' . $form_group_class;
}
$select .= '<div class="select-placeholder form-group' . $form_group_class . '" ' . $_form_group_attr . '>';
if ($label != '') {
$select .= '<label for="' . $name . '" class="control-label">' . _l($label, '', false) . '</label>';
}
$select .= '<select id="' . $name . '" name="' . $name . '" class="selectpicker' . $select_class . '" ' . $_select_attrs . ' data-live-search="true">';
if ($include_blank == true) {
$select .= '<option value=""></option>';
}
foreach ($options as $option) {
$val = '';
$_selected = '';
$key = '';
if (isset($option[$option_attrs[0]]) && !empty($option[$option_attrs[0]])) {
$key = $option[$option_attrs[0]];
}
if (!is_array($option_attrs[1])) {
$val = $option[$option_attrs[1]];
} else {
foreach ($option_attrs[1] as $_val) {
$val .= $option[$_val] . ' ';
}
}
$val = trim($val);
if ($callback_translate != '') {
if (function_exists($callback_translate) && is_callable($callback_translate)) {
$val = call_user_func($callback_translate, $key);
}
}
$data_sub_text = '';
if (!is_array($selected)) {
if ($selected != '') {
if ($selected == $key) {
$_selected = ' selected';
}
}
} else {
foreach ($selected as $id) {
if ($key == $id) {
$_selected = ' selected';
}
}
}
if (isset($option_attrs[2])) {
if (strpos($option_attrs[2], ',') !== false) {
$sub_text = '';
$_temp = explode(',', $option_attrs[2]);
foreach ($_temp as $t) {
if (isset($option[$t])) {
$sub_text .= $option[$t] . ' ';
}
}
} else {
if (isset($option[$option_attrs[2]])) {
$sub_text = $option[$option_attrs[2]];
} else {
$sub_text = $option_attrs[2];
}
}
$data_sub_text = ' data-subtext=' . '"' . $sub_text . '"';
}
$data_content = '';
if (isset($option['option_attributes'])) {
foreach ($option['option_attributes'] as $_opt_attr_key => $_opt_attr_val) {
$data_content .= $_opt_attr_key . '=' . '"' . $_opt_attr_val . '"';
}
if ($data_content != '') {
$data_content = ' ' . $data_content;
}
}
$select .= '<option value="' . $key . '"' . $_selected . $data_content . $data_sub_text . '>' . $val . '</option>';
}
$select .= '</select>';
$select .= '</div>';
return $select;
}
get sellers arrays in db functions
function get_sellers()
{
$CI = & get_instance();
return $CI->db->get(db_prefix() . 'sellers')->result_array();
}
I have created a column "sellers" in my table but it sends numbers and not text.
I need it so that when the form is saved it will submit the title and display it in the selection.
Thanks you
View form:
click

PHP Leaderboard add (t) for ties

I have a php leaderboard and it works great, and works well with ties. Currently it will number users from 1st to last place (whichever # that is), and if there are ties, it lists them all out with the same number.
For example:
userC 2. userG 3. userA 3. userT 3. userJ 4. userW 5. userP
What I would like is for when there are ties, for the leaderboard to display a "(t)" next to the number, like so: (t) 3. userT
Here is my code, any help is appreciated:
<table cellpadding="4" cellspacing="0" class="table1" width="100%"><caption>
<h2>Leaderboard</h2>
</caption>
<tr><th align="left">Player</th><th align="left">Wins</th><th>Pick Ratio</th></tr>
<?php
if (isset($playerTotals)) {
$playerTotals = sort2d($playerTotals, 'score', 'desc');
$i = 1;
$tmpScore = 0;
//show place #
foreach($playerTotals as $playerID => $stats) {
if ($tmpScore < $stats[score]) $tmpScore = $stats[score];
//if next lowest score is reached, increase counter
if ($stats[score] < $tmpScore ) $i++;
$pickRatio = $stats[score] . '/' . $possibleScoreTotal;
$pickPercentage = number_format((($stats[score] / $possibleScoreTotal) * 100), 2) . '%';
//display users/stats
$rowclass = ((($i - 1) % 2 == 0) ? ' class="altrow"' : '');
echo ' <tr' . $rowclass . '><td style="height: 25px;"><b>' . $i . '</b>. ' . $stats[userName] . '</td><td align="center">' . $stats[wins] . '</td><td align="center">' . $pickRatio . ' (' . $pickPercentage . ')</td></tr>';
$tmpScore = $stats[score];
}
}
echo ' </div>' . "\n";
?>
</table>
Try this code... hope it will resolve your issue
<table cellpadding="4" cellspacing="0" class="table1" width="100%">
<caption><h2>Leaderboard</h2></caption>
<tr><th align="left">Player</th><th align="left">Wins</th><th>Pick Ratio</th></tr>
<?php
if (isset($playerTotals)) {
$playerTotals = sort2d($playerTotals, 'score', 'desc');
$j = 1;
$tmpScore = 0;
//show place #
$tieflag=false;
for($i=0; $i<=count($playerTotals)-1; $i++) {
if(($i<count($playerTotals) && $playerTotals[$i][score]==$playerTotals[$i+1][score]) || ($i>0 && $playerTotals[$i][score]==$playerTotals[$i-1][score])) $tieflag=true;
$pickRatio = $$playerTotals[$i][score] . '/' . $possibleScoreTotal;
$pickPercentage = number_format((($playerTotals[$i][score] / $possibleScoreTotal) * 100), 2) . '%';
$rowclass = ((($j - 1) % 2 == 0) ? ' class="altrow"' : '');
echo ' <tr' . $rowclass . '><td style="height: 25px;"><b>' . ($tieflag?'(t)'.$j:$j) . '</b>. ' . $playerTotals[$i][userName] . '</td><td align="center">' . $playerTotals[$i][wins] . '</td><td align="center">' . $pickRatio . ' (' . $pickPercentage . ')</td></tr>';
$j++;
}
}
echo '</div>'. "\n";
?>
</table>
I'd create a new variable $placeholder. So:
if ( $i != 0 ) {
if ($tmpScore < $stats[score]) {
$tmpScore = $stats[score];
}
if ( $tmpScore == $stats[score] ) {
$placeholder = $i.'(t)';
} else if ($stats[score] < $tmpScore )
$placeholder = $++i;
}
} else {
$placeholder = $++i;
$firstScore = $stats[score];
$tmpScore = $stats[score];
}
Then instead of printing $i print $placeholder
so for the first time through you could do this in the echo:
//It makes more sense if you read it from bottom to top but I put it this way
//so you will not have to keep running through every condition when you will
//only evaluate the first condition most often
if ( $i != 0 && $i != 1 ) {
echo ;//Your normal print
} else if ( $i = 1 && $tmpScore != $firstScore ) {
echo '<b>'; //and the rest of the first line plus second line NOT a tie
} else if ( $i = 1 ) {
echo ' (t)'; //Plus the rest of your first line plus second line TIE
} else {
//This is your first time through the loop and you don't know if it's a tie yet so just
//Print placeholder and then wait to figure out the rest
echo ' <tr' . $rowclass . '><td style="height: 25px;"><b>' . $placeholder;
}

How To Change Numbers Based On Results

I have a follow up question on something I got help with here the other day (No Table Three Column Category Layout).
The script is as follows:
$res = mysql_query($query);
$system->check_mysql($res, $query, __LINE__, __FILE__);
$parent_node = mysql_fetch_assoc($res);
$id = (isset($parent_node['cat_id'])) ? $parent_node['cat_id'] : $id;
$catalist = '';
if ($parent_node['left_id'] != 1)
{
$children = $catscontrol->get_children_list($parent_node['left_id'], $parent_node['right_id']);
$childarray = array($id);
foreach ($children as $k => $v)
{
$childarray[] = $v['cat_id'];
}
$catalist = '(';
$catalist .= implode(',', $childarray);
$catalist .= ')';
$all_items = false;
}
$NOW = time();
/*
specified category number
look into table - and if we don't have such category - redirect to full list
*/
$query = "SELECT * FROM " . $DBPrefix . "categories WHERE cat_id = " . $id;
$result = mysql_query($query);
$system->check_mysql($result, $query, __LINE__, __FILE__);
$category = mysql_fetch_assoc($result);
if (mysql_num_rows($result) == 0)
{
// redirect to global categories list
header ('location: browse.php?id=0');
exit;
}
else
{
// Retrieve the translated category name
$par_id = $category['parent_id'];
$TPL_categories_string = '';
$crumbs = $catscontrol->get_bread_crumbs($category['left_id'], $category['right_id']);
for ($i = 0; $i < count($crumbs); $i++)
{
if ($crumbs[$i]['cat_id'] > 0)
{
if ($i > 0)
{
$TPL_categories_string .= ' > ';
}
$TPL_categories_string .= '' . $category_names[$crumbs[$i]['cat_id']] . '';
}
}
// get list of subcategories of this category
$subcat_count = 0;
$query = "SELECT * FROM " . $DBPrefix . "categories WHERE parent_id = " . $id . " ORDER BY cat_name";
$result = mysql_query($query);
$system->check_mysql($result, $query, __LINE__, __FILE__);
$need_to_continue = 1;
$cycle = 1;
$column = 1;
$TPL_main_value = '';
while ($row = mysql_fetch_array($result))
{
++$subcat_count;
if ($cycle == 1)
{
$TPL_main_value .= '<div class="col'.$column.'"><ul>' . "\n";
}
$sub_counter = $row['sub_counter'];
$cat_counter = $row['counter'];
if ($sub_counter != 0)
{
$count_string = ' (' . $sub_counter . ')';
}
else
{
if ($cat_counter != 0)
{
$count_string = ' (' . $cat_counter . ')';
}
else
{
$count_string = '';
}
}
if ($row['cat_colour'] != '')
{
$BG = 'bgcolor=' . $row['cat_colour'];
}
else
{
$BG = '';
}
// Retrieve the translated category name
$row['cat_name'] = $category_names[$row['cat_id']];
$catimage = (!empty($row['cat_image'])) ? '<img src="' . $row['cat_image'] . '" border=0>' : '';
$TPL_main_value .= "\t" . '<li>' . $catimage . '' . $row['cat_name'] . $count_string . '</li>' . "\n";
++$cycle;
if ($cycle == 7) // <---- here
{
$cycle = 1;
$TPL_main_value .= '</ul></div>' . "\n";
++$column;
}
}
if ($cycle >= 2 && $cycle <= 6) // <---- here minus 1
{
while ($cycle < 7) // <---- and here
{
$TPL_main_value .= ' <p> </p>' . "\n";
++$cycle;
}
$TPL_main_value .= '</ul></div>'.$number.'
' . "\n";
}
I was needing to divide the resulting links into three columns to fit my html layout.
We accomplished this by changing the numbers in the code marked with "// <---- here".
Because the amount of links returned could be different each time, I am trying to figure out how to change those numbers on the fly. I tried using
$number_a = mysql_num_rows($result);
$number_b = $number_a / 3;
$number_b = ceil($number_b);
$number_c = $number_b - 1;
and then replacing the numbers with $number_b or $number_c but that doesn't work. Any ideas?
As mentioned before, you can use the mod (%) function to do that.
Basically what it does is to get the remainder after division. So, if you say 11 % 3, you will get 2 since that is the remainder after division. You can then make use of this to check when a number is divisible by 3 (the remainder will be zero), and insert an end </div> in your code.
Here is a simplified example on how to use it to insert a newline after every 3 columns:
$cycle = 1;
$arr = range (1, 20);
$len = sizeof ($arr);
for ( ; $cycle <= $len; $cycle++)
{
echo "{$arr[$cycle - 1]} ";
if ($cycle % 3 == 0)
{
echo "\n";
}
}
echo "\n\n";

Is there a better loop I could write to reduce database queries?

Below is some code I've written that is effective, but makes too many database queries. Is there a way I could optimize and reduce the number of queries but have conditional statements still be as effective as below?
I pasted the code repeated a few times just for good measure.
echo "<h3>Pool Packages</h3>";
echo "<ul>";
foreach ($items as $item):
$this->db->where('id', $item['id']);
$query = $this->db->get('items')->row();
if ($item['quantity'] > 1 && $item['quantity'] == TRUE && $query->category == "Pool Packages") {
$newprice = $item['quantity'] * $query->price;
$totals[] = $newprice;
}
else {
$newprice = $query->price;
$totals[] = $newprice;
}
if ($query->category == "Pool Packages") {
echo "<li>" . $query->name . " (QTY: " . $item['quantity'] . " x = " . str_ireplace(" ", "", money_format('%(#10n', $newprice)) . ")</li>";
}
else { }
endforeach;
echo "</ul>";
echo "<h3>Water Features</h3>";
echo "<ul>";
foreach ($items as $item):
$this->db->where('id', $item['id']);
$query = $this->db->get('items')->row();
if ($item['quantity'] > 1 && $item['quantity'] == TRUE && $query->category == "Water Features") {
$newprice = $item['quantity'] * $query->price;
$totals[] = $newprice;
}
else {
$newprice = $query->price;
$totals[] = $newprice;
}
if ($query->category == "Water Features") {
echo "<li>" . $query->name . " (QTY: " . $item['quantity'] . " x = " . str_ireplace(" ", "", money_format('%(#10n', $newprice)) . ")</li>";
}
else { }
endforeach;
echo "</ul>";
echo "<h3>Waterfall Rock Work</h3>";
echo "<ul>";
foreach ($items as $item):
$this->db->where('id', $item['id']);
$query = $this->db->get('items')->row();
if ($item['quantity'] > 1 && $item['quantity'] == TRUE) {
$newprice = $item['quantity'] * $query->price;
$totals[] = $newprice;
}
else {
$newprice = $query->price;
$totals[] = $newprice;
}
if ($query->category == "Waterfall Rock Work") {
echo "<li>" . $query->name . " (QTY: " . $item['quantity'] . " x = " . str_ireplace(" ", "", money_format('%(#10n', $newprice)) . ")</li>";
}
else { }
endforeach;
echo "</ul>";
echo "<h3>Sheer Descents</h3>";
echo "<ul>";
foreach ($items as $item):
$this->db->where('id', $item['id']);
$query = $this->db->get('items')->row();
if ($item['quantity'] > 1 && $item['quantity'] == TRUE && $query->category == "Sheer Descents") {
$newprice = $item['quantity'] * $query->price;
$totals[] = $newprice;
}
else {
$newprice = $query->price;
$totals[] = $newprice;
}
if ($query->category == "Sheer Descents") {
echo "<li>" . $query->name . " (QTY: " . $item['quantity'] . " x = " . str_ireplace(" ", "", money_format('%(#10n', $newprice)) . ")</li>";
}
else { }
endforeach;
echo "</ul>";
echo "<h3>Booster Pump</h3>";
echo "<ul>";
foreach ($items as $item):
$this->db->where('id', $item['id']);
$query = $this->db->get('items')->row();
if ($item['quantity'] > 1 && $item['quantity'] == TRUE && $query->category == "Booster Pump") {
$newprice = $item['quantity'] * $query->price;
$totals[] = $newprice;
}
else {
$newprice = $query->price;
$totals[] = $newprice;
}
if ($query->category == "Booster Pump") {
echo "<li>" . $query->name . " (QTY: " . $item['quantity'] . " x = " . str_ireplace(" ", "", money_format('%(#10n', $newprice)) . ")</li>";
}
else { }
endforeach;
echo "</ul>";
echo "<h3>Pool Concrete Decking</h3>";
echo "<ul>";
foreach ($items as $item):
$this->db->where('id', $item['id']);
$query = $this->db->get('items')->row();
if ($item['quantity'] > 1 && $item['quantity'] == TRUE && $query->category == "Pool Concrete Decking") {
$newprice = $item['quantity'] * $query->price;
$totals[] = $newprice;
}
else {
$newprice = $query->price;
$totals[] = $newprice;
}
if ($query->category == "Pool Concrete Decking") {
echo "<li>" . $query->name . " (QTY: " . $item['quantity'] . " x = " . str_ireplace(" ", "", money_format('%(#10n', $newprice)) . ")</li>";
}
else { }
endforeach;
echo "</ul>";
echo "<h3>Solar Heating</h3>";
echo "<ul>";
foreach ($items as $item):
$this->db->where('id', $item['id']);
$query = $this->db->get('items')->row();
if ($item['quantity'] > 1 && $item['quantity'] == TRUE && $query->category == "Solar Heating") {
$newprice = $item['quantity'] * $query->price;
$totals[] = $newprice;
}
else {
$newprice = $query->price;
$totals[] = $newprice;
}
if ($query->category == "Solar Heating") {
echo "<li>" . $query->name . " (QTY: " . $item['quantity'] . " x = " . str_ireplace(" ", "", money_format('%(#10n', $newprice)) . ")</li>";
}
else { }
endforeach;
echo "</ul>";
echo "<h3>Raised Bond Beam</h3>";
echo "<ul>";
foreach ($items as $item):
$this->db->where('id', $item['id']);
$query = $this->db->get('items')->row();
if ($item['quantity'] > 1 && $item['quantity'] == TRUE && $query->category == "Raised Bond Beam") {
$newprice = $item['quantity'] * $query->price;
$totals[] = $newprice;
}
else {
$newprice = $query->price;
$totals[] = $newprice;
}
if ($query->category == "Raised Bond Beam") {
echo "<li>" . $query->name . " (QTY: " . $item['quantity'] . " x = " . str_ireplace(" ", "", money_format('%(#10n', $newprice)) . ")</li>";
}
else { echo "<li>None</li>"; }
endforeach;
echo "</ul>";
It goes on beyond this to several more categories, but I don't know how to handle looping through this best. Thanks!
You could build the html in a variable so you only loop once. Here's a quick and dirty example just to show you what I'm talking about:
$html = '';
$oldCat = '';
foreach ($items as $item) {
$this->db->where('id', $item['id']);
$query = $this->db->get('items')->row();
if ($oldCat != $query->category) {
$html .= "</ul>\n";
$html .= "<h3>".$query->category."</h3>\n<ul>\n";
$oldCat = $query->category;
}
if ($item['quantity'] > 0) {
$newprice = $item['quantity'] * $query->price;
$totals[] = $newprice;
}
$html .= "<li>" . $query->name . " (QTY: " . $item['quantity'] . " x = " . str_ireplace(" ", "", money_format('%(#10n', $newprice)) . ")</li>\n";
}
// strip leading /ul, append a /ul, echo html
You could store all the rows into a separate array during the first loop and then reference the array throughout all the other loops rather than fetching the same information over and over, assuming you're select * which you probably are.
Or, if there are not many items more than the ones you're fetching, you could use a single query to fetch all of the rows at once (you're using only one query) and loop through that to store all the values in an array $array[$row['id']] = $row (or something similar) then simply reference all those rows in the array in each of your loops.
You need to start thinking in terms of sets instead of loops. Write a stored proc that takes the array either as a varchar (or in SQL Server 2008 you can use a table valued input parameter, don't know about other dbs).
Then split the string into a temp table and return all the records in one select joining to the temp table. Even if you need to return separate record sets, doing it in a stored proc will reduce the network traffic in.
you should use a join from items to category and get all the items, then you can sort them out into a multi-dimensional array and then loop through that for output.
Im not sure what youre classes db connection is doing but but lets assume we want all items with thier category:
$sql = "SELECT item.*, category.name as category from item, category WHERE item.category_id = category.item_id";
// ill use PDO for db access here...
$db = new PDO($connString, $username, $password);
$items = array(); // our array indexed by category.
foreach($db->query($sql) as $item) {
if(!array_key_exists($items, $item['category']) {
$items[$item['category']] = array();
}
$items[$item['category']][] = $item;
}
// now loop through $items using the similar stuff you did for output previously.
// note instead of doing the conditionals for pricing and stuff here you may want to
// do that in the loop above and put it in the array before hand... it will keep the
// output loop cleaner.

Categories