Show selected in multiple selection in PHP loop - php

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 .'>';

Related

Setting an If Statement with AJAX in PHP

I am nearing completion of this code / plugin and I just have one bit to finish up before we make it all pretty and presentable; I am attempting to get my PHP file to re-load/re-fresh with the POST variables sent from the AJAX file, all from the response of the AJAX send:
$("#CategoryTree").load("poster.php #CategoryTree");
Right now on clicking a list item the CSS fires, the ajax fires and responds, variables are sent (checked them in the action registry as well all good there) but the area I call to re-load with the poster.php #CategoryTree does not react, error 500 is thrown.
Here is my full Javascript code:
jQuery(document).ready(function($) {
$('#CategoryTree').on('click', 'input[type=checkbox]', function() {
var $this = $(this);
var data = '';
if ($this.is(":checked")) {
$this.addClass('selectCheckbox');
//$this.val("1");
data = {
action: 'catID_Callback',
catID: $this.attr('id'),
catState: 1
};
$.post(the_ajax_script.ajaxurl, data, function(response) {
//alert('Got this from the server: ' + response);
$("#CategoryTree").load("poster.php #CategoryTree");
//alert( "Load was performed." );});
console.log(response);
});
} else {
$this.removeClass('selectCheckbox');
//$this.val("0");
data = {
action: 'catID_Callback',
catID: $this.attr('id'),
catState: 0
};
$.post(the_ajax_script.ajaxurl, data, function(response) {
// alert('Got this from the server: ' + response);
console.log(response);
});
}
});
});
And here is the PHP code (Line 55 is where the check starts):
<?php
//$message = "Started";
//echo "<script type='text/javascript'>alert('$message');</script>";
$thearray = [];
$terms = get_terms("pa_mymelp");
foreach ( $terms as $term ) {
$categories = $term->name;
array_push($thearray, $categories);
}
$categoryLines = $thearray;
function buildCategoryTree($categoryLines, $separator) {
$catTree = array();
foreach ($categoryLines as $catLine) {
$path = explode($separator, $catLine);
$node = & $catTree;
foreach ($path as $cat) {
$cat = trim($cat);
if (!isset($node[$cat])) {
$node[$cat] = array();
}
$node = & $node[$cat];
}
}
return $catTree;
}
function displayCategoryTree($categoryTree, $indent = '') {
foreach ($categoryTree as $node => $children) {
echo $indent . $node . "\n";
displayCategoryTree($children, $indent . '|- ');
}
}
$categoryTree = buildCategoryTree($categoryLines, '/');
function displayHtmlCategoryTree($categoryTree, $id = null, $pathSeparator = '/', $parents = '') {
if (empty($categoryTree)) return '';
$str = '<ul' . (!empty($id) ? ' id="'.$id.'"' : '') . '>';
foreach ($categoryTree as $node => $children) {
$currentPath = $parents . (empty($parents) ? '' : $pathSeparator) . $node;
$thelink = '';
$opener = 0;
if (substr_count($currentPath, '/')==5){
$patterns = array(" ", "/", ".");
$thelink = 'http://caap.co.nz/?pa_mymelp=' . strtolower(str_replace($patterns, '-', $currentPath));
$str .= '<li title="' . $currentPath . '">' . '<input value ="0" class="first" type="checkbox" id="' . $currentPath . '">' . '<label for="' . $currentPath . '">' . '' . $node . '</label>' .
/*displayHtmlCategoryTree($children, null, $pathSeparator, $currentPath) .
*/'</li>';}
else
{
$cat = 0;
$catState = 0;
if (isset($_POST['catID'])){
$cat = $_POST['catID'];
}
if (isset($_POST['catState'])){
$catState = $_POST['catState'];
}
$str .= '<li title="' . $currentPath . '">' . '<input value="0" class="first" type="checkbox" id="' . $currentPath . '">' . '<label for="' . $currentPath . '">' . $node . '</label>';
if ($cat == $currentPath && $catState == 1 ){$str.=displayHtmlCategoryTree($children, null, $pathSeparator, $currentPath);}
}
}
$str .= '</li></ul>';
return $str;
}
echo displayHtmlCategoryTree($categoryTree, "CategoryTree", '/');
/*
function add_query_vars_filter( $vars ){
foreach (array_keys(Contracts::$query_params) as $name)
$vars[] = $name;
return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );
*/
?>
Here is the pertinent code from the PHP file
$cat = 0;
$catState = 0;
if (isset($_POST['catID'])){
$cat = $_POST['catID'];
}
if (isset($_POST['catState'])){
$catState = $_POST['catState'];
}
$str .= '<li title="' . $currentPath . '">' . '<input value="0" class="first" type="checkbox" id="' . $currentPath . '">' . '<label for="' . $currentPath . '">' . $node . '</label>';
if ($cat == $currentPath && $catState == 1 ){$str.=displayHtmlCategoryTree($children, null, $pathSeparator, $currentPath);}
Remove semicolon after if curly braces. if{}; to if{}
if (isset($_POST['catID'])){$cat = $_POST['catID'];};
replace it to
if (isset($_POST['catID'])){
$cat = $_POST['catID'];
}
Now your code looks like.
if (isset($_POST['catID'])){
$cat = $_POST['catID'];
}
if (isset($_POST['catState'])){
$catState = $_POST['catState'];
}
$str .= '<li title="' . $currentPath . '">' . '<input value="0" class="first" type="checkbox" id="' . $currentPath . '">' . '<label for="' . $currentPath . '">' . $node . '</label>';
if ($cat == $currentPath && $catState == 1){
$str.=displayHtmlCategoryTree($children, null, $pathSeparator, $currentPath);
}

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

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>';

PHP Bootstrap multi select options

In my code I am using PHP which populates the bootstrap multi selectpicker from MySQL database but the problem is it only selects the last option instead of multiple options, I don't know what I am missing in it? Here is my my code
function MultiBindCombo($tablenames, $columnnames1, $columnnames2, $comboname, $selectedopt) {
global $conn;
$sql="SELECT ". $columnnames1. ", " . $columnnames2 . " FROM ". $tablenames;
$result = mysqli_query($conn, $sql);
if( ! $result ) {
echo mysql_error();
exit;
}
echo '<select class="selectpicker form-control" data-live-search="true" name="' . $comboname . '" multiple="multiple">';
$array = explode(',', $selectedopt);
while ($row=mysqli_fetch_array($result)) {
foreach ($array as $select_option){
if($row[$columnnames1] == $select_option) {
$print_selected = 'selected';
} else {
$print_selected = '';
}
echo $select_option;
}
echo '<option data-tokens="' . $row[$columnnames1] . '" value="' . $row[$columnnames1] . '"' .$print_selected. '>' . $row[$columnnames2] . '</option>';
}
echo '</select>';
}
To get all selected values in a multiselect you need to use name attribute with []:
echo '<select class="selectpicker form-control" data-live-search="true" name="' . $comboname . '[]" multiple="multiple">';
After that you can iterate over $_POST[$comboname] with a foreach.
Update:
Let's look closer to your code here:
while ($row=mysqli_fetch_array($result)) {
foreach ($array as $select_option){
// You iterate over every value of array, so in the end
// `$print_selected` is defined depending on value of the
// last `$select_option`
if($row[$columnnames1] == $select_option) {
$print_selected = 'selected';
} else {
$print_selected = '';
}
// remove this. Why you echo `$select_option`?
echo $select_option;
}
echo '<option data-tokens="' . $row[$columnnames1] . '" value="' . $row[$columnnames1] . '"' .$print_selected. '>' . $row[$columnnames2] . '</option>';
}
Rewrite it as:
while ($row=mysqli_fetch_array($result)) {
$print_selected = '';
foreach ($array as $select_option){
if($row[$columnnames1] == $select_option) {
$print_selected = 'selected';
// break `foreach` as you found the right item
break;
}
}
// if right item is not found - `$print_selected` is empty
echo '<option data-tokens="' . $row[$columnnames1] . '" value="' . $row[$columnnames1] . '"' .$print_selected. '>' . $row[$columnnames2] . '</option>';
}

php dropdown menu with deafult selected value

I am working on a PHP project as follows
if( mysql_num_rows( $result ) > 0 ) {
echo '<select name="officerlist">';
while ( $rows = mysql_fetch_array ( $result ) ) {
echo '<option>' . $rows['officer'] . '</option>';
if ($types[ $maxindex ] == $rows['officer']){
echo ' selected';
}
}
echo '</select>';
}
I am able to populate the query result into the dropdown menu. However, I want to implement it to have a default selected value based on value from another array. (ie if $types[$maxindex] is found in $rows['officer'], it will auto select the value.).
Anyone able to advise?
Thank you and best regards!
try this
if( mysql_num_rows($result)>0 ) {
echo '<select name="officerlist">';
while ( $rows = mysql_fetch_array ($result) ) {
if ($types[$maxindex] == $rows['officer']){
echo '<option selected="selected">' . $rows['officer'] . '</option>';
}
else
{
echo '<option>' . $rows['officer'] . '</option>';
}
}
echo '</select>';
should be like this,
while ( $rows = mysql_fetch_array ($result) ) {
if ($types[$maxindex] == $rows['officer']){
echo '<option selected="selected" value="'.$rows['officer'].'">' . $rows['officer'] . '</option>';
} else {
echo '<option value="'.$rows['officer'].'">' . $rows['officer'] . '</option>';
}
}
You need add the selected attribute inside the <option> tag, like
<option selected='selected'>youroption</option>.
Try this,
if( mysql_num_rows($result)>0 ) {
echo '<select name="officerlist">';
while ( $rows = mysql_fetch_array ($result) ) {
$selected ="";
if ($types[$maxindex] == $rows['officer']){
$selected = ' selected="selected" ';
}
echo '<option '.$selected.'>' . $rows['officer'] . '</option>';
}
echo '</select>';
}
while ( $rows = mysql_fetch_array ($result) ) {
if ($types[$maxindex] == $rows['officer']){
echo '<option SELECTED>' . $rows['officer'] . '</option>';
} else {
echo '<option>' . $rows['officer'] . '</option>';
}
}

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