PHP - Iterating through db result associative array - php

I was wondering if someone could help me. I want to iterate through an associative array and put the results into two combo boxes. The combo boxes will have the exact same data in each other.
while ($this->results = $this->dbhandle->fetch(PDO::Fetch_Assoc))
{
echo "<option value='" . $this->result['id] . "'>"
. $this->result['name'] . "</option>";
}
Do I have to run this loop twice for 2 seperate comboboxes or is there a more efficient way of doing this?

Your best bet in this situation is to just accumulate the text in a string and echo it out twice.
$options = "";
while ($this->results = $this->dbhandle->fetch(PDO::Fetch_Assoc))
{
$options.= "<option value='" . $this->result['id] . "'>"
. $this->result['name'] . "</option>";
}
echo "<select name='combo1'>".$options."</select>";
echo "<select name='combo2'>".$options."</select>";

How about something like this (raw code to give you an idea):
while
{
$combo_options .= "<option>" ....// rest of your code
}
Then print the variable inside your selects:
<select id="combo1"><?=$combo_options?></select>
<select id="combo2"><?=$combo_options?></select>

You can capture the output as a variable and then echo it as needed
while ($this->results = $this->dbhandle->fetch(PDO::FetchAssoc)){
$output .= "<option value='" . $this->result['id'] . "'>" . $this->result['name'] . "</option>";
}
/// later on in your script
print $output;

Related

Get data from form using PHP

I have a php file that creates a table for me using data fetched from a mysql database.
<?php
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['CountryCode'] . "</td>";
echo "<td>" . $row['District'] . "</td>";
echo "<td>" . $row['Population'] . "</td>";
echo "<td>" . $row['Price'] . "</td>";
echo "<td><input type=\"number\" name="quantity" id="quantity"></td>";
echo "</tr>";
}
} else {
echo "0 results";
}
$conn->close();
?>
At the end of each row, I have an input number so that I can calculate the amount of each product(countries in this case). How could I get the amount of each country, multiply it by the price and return a total at the end of my table?
If you want to do it with PHP, you have to do it in two steps, because the PHP is processed in the server. So you would enter all the quantities you want and when you press the "Compute" button, the page would send all the values to the server who would compute everything you want and give you the final result.
A problem that I see with this solution is that once you have get all the quantities you want, you would have to get the prices once more. I don't its very efficient because you already have them on the first page. I see two solutions here :
When you display the values, keep track of the prices in a $_SESSION field, thus you will be able to access them after leaving the page, without having to get them from the database.
When you display the values, display the prices in an input field (I would recommend as readonly so that the user won't change this value here), and thus they would be included in the $_POST (or $_GET, if you use this) variable that your browser would send to the server.
If you're only interested to display the value, without using it after, you can use javascript to compute it, it might be easier.
Even though it's not the point here, you should be careful when displaying inputs via PHP on a while loop, because here all of your inputs have the same id, which would make thing harder to compute what you want to.
Hope it helps!
You must add a form tag around the table and then sum record price * qty on every row
What I did here is I checked if the quantity is set in the POST variable or not. if it exists I put data in quantity value. after that, you must make the name of quantity capable of taking array inside with the key of record Id.
after that, if the form submitted the quantity will send back to the page as a query string. then I multiply the price with quantity and add it to sum varaible. after finishing the loop and echo out the sum variable at the end of the table.
$html = '';
if ($result->num_rows > 0) {
$html .= '<form method="GET" action="" target="_self>';
$row = $result->fetch_assoc();
if(isset($_GET['quantity'][$row['ID']]))
$qty = $_GET['quantity'][$row['ID']];
else
$qty = 0;
$sum = 0;
// output data of each row
while ($row) {
$html .= '<tr>';
$html .= '<td>' . $row['ID'] . '</td>';
$html .= '<td>' . $row['Name'] . '</td>';
$html .= '<td>' . $row['CountryCode'] . '</td>';
$html .= '<td>' . $row['District'] . '</td>';
$html .= '<td>' . $row['Population'] . '</td>';
$html .= '<td>' . $row['Price'] . '</td>';
$html .= '<td>
<input type="number" name="quantity[' . $row['ID'] . ']" value="' . $qty . '">
</td>';
$html .= '<td>' . ($sum += $row['Price'] * $qty) . '</td>';
$html .= '</tr>';
}
$html .= '<input name="submitForm" value="submitForm">';
$html .= '</form>';
$html .= '<tr>';
$html .= '<td>Total = '.$sum.'</td>';
$html .= '</tr>';
} else {
$html .= "0 results";
}
$conn->close();
echo htmlspecialchars($html);
remember to use htmlspecialchars to echo out the result.

Php wrong value

I am using the following code. I take some values from an xml, then I use as html option. I am using almost the same code for the first and second select. First option show in the select menu the right values: http://vilavaleaprahovei.ro/kimea/anvelope.php, but the other one shows 0. Could somebody to tell me what to do on the "Eficienta combustibil" to show the right values?
<form action="anvelope.php" method="post">
<?php
$jante = "http://vilavaleaprahovei.ro/kimea/feeds/alcarRO_feed.xml";
$xml=simplexml_load_file($jante);
$items = [];
$limitItems = 0;
foreach($xml->Produs as $child)
{
$marca = (string)$child->Marca;
if(!isset($items[$marca])) {
$items[$marca] = [];
}
$items[$marca]['sarcina'][] = (int)$child->Sarcina;
$items[$marca]['eficienta_combustibil'][] = (float)$child->Eficienta_Combustibil;
}
//SARCINA
$option_arr9 = array_column($items,'sarcina');
function generate_option9($item, $key)
{
echo "<option value='" . $item . "'>" . $item . "</option>";
}
$options = array_unique($option_arr9[0], SORT_STRING); // You can add array_unique and SORT_NUMERIC here
asort($options);
echo "<select name='sarcina'><option>Sarcina</option>";
array_walk_recursive($options, 'generate_option9');
echo "</select>";
//EFICIENTA COMBUSTIBIL
$option_arr10 = array_column($items,'eficienta_combustibil');
function generate_option10($item, $key)
{
echo "<option value='" . $item . "'>" . $item . "</option>";
}
$options = array_unique($option_arr10[3], SORT_STRING); // You can add array_unique and SORT_NUMERIC here
asort($options);
echo "<select name='eficienta_combustibil'><option>Eficienta Combustibil</option>";
array_walk_recursive($options, 'generate_option10');
echo "</select>";
?>
</form>

Echo nested array's with foreach PHP

I have seen many similar issues but none that can help explain my issue.
I have an array called cities, with a nested array for the state that has the cities of that state. It looks like this:
$cities = array(
"ca" => array(
"los-angeles" => "Los Angeles"
),
"wa" => array(
"bellingham" => "Bellingham",
"seattle" => "Seattle",
"tacoma" => "Tacoma"
)
);
My PHP code to display many HTML select fields:
<?php
foreach ($cities as $state) {
echo "<select name='city' id='" . $state . "'>";
foreach ($state as $city => $name) {
echo "<option value='" . $city . "'>" . $name . "</option>";
}
}
?>
The id of the select is always Array. How can I use the key, like "ca" or "wa"?
The problem is that you should be using the array key for the select on the states. Here is my revision of your code. Note that I explicitly have named state_key and state_value as well as city_key and city_value. Naming things explicitly like this helps in debugging. I also added a closing </select> element so the content renders correctly.
foreach ($cities as $state_key => $state_value) {
echo "<select name='city' id='" . $state_key . "'>";
foreach ($state_value as $city_key => $city_value) {
echo "<option value='" . $city_key . "'>" . $city_value . "</option>";
}
echo "</select>";
}
That's because the first foreach loop is going over an array of arrays. So each member is going to be an array. If you had id ='" . $state[0] you would see the first member of said array.
the var_dump function is your friend.
You could get all the cities by using array_keys function.
foreach ($cities as $key=>$state) {
echo "<select name='city' id='" . $key . "'>";
foreach ($state as $city => $name) {
echo "<option value='" . $city . "'>" . $name . "</option>";
}
}
change to this
in your case $state is an array containing cities. so it is always showing the value as Array().
Try uisng echo "<select name='city' id='" . $state['los-angeles'] . "'>"; instead of echo "<select name='city' id='" . $state . "'>";
If you want ca as your select element id then use below one,
foreach ($cities as $key=>$state) {
echo "<select name='city' id='" . $key . "'>";
foreach ($state as $city => $name) {
echo "<option value='" . $city . "'>" . $name . "</option>";
}
}
If you want like los-angeles as id of your select element, then use below one
foreach ($cities as $key=>$state) {
$SelectId = strtolower(str_replace(" ",'-',$state['los-angeles']));
echo "<select name='city' id='" . $SelectId . "'>";
foreach ($state as $city => $name) {
echo "<option value='" . $city . "'>" . $name . "</option>";
}
}

error with strpos on form

I'm coding the locations for groups, and the user can search based on the location to find the nearest group to them. The fields are: country, state, city, neighborhood. Let's say there are ten groups in the USA -- I don't want it to list the option USA ten times. I added in a strpos so that it will only list them once, but I'm getting an error.
Here's the php code:
<?php
$myQuery = "select country, state, city, neighborhood from groups WHERE group_status = 'open to new members'";
$rs = mysql_query($myQuery);
$country_options = $state_options = $city_options = $neighborhood_options = '';
while($get_row = mysql_fetch_assoc($rs)){
$pos_country = strpos($get_row['country'], $country_options);
if($pos_country === false) {
echo $country_options .= "<option value='" . $get_row['country'] . "'>" . $get_row['country'] . "</option>";}
$pos_state = strpos($get_row['state'], $state_options);
if($pos_state === false) {
echo $state_options .= "<option value='" . $get_row['state'] . "'>" . $get_row['state'] . "</option>";}
$pos_city = strpos($get_row['city'], $city_options);
if($pos_city === false) {
echo $city_options .= "<option value='" . $get_row['city'] . "'>" . $get_row['city'] . "</option>";}
$pos_neighborhood = strpos($get_row['neighborhood'], $neighborhood_options);
if($pos_neighborhood === false) {
echo $neighborhood_options .= "<option value='" . $get_row['neighborhood'] . "'>" . $get_row['neighborhood'] . "</option>";}
}
?>
It outputs the following errors:
Warning: strpos(): Empty delimiter in sidebar.php on line 66
Warning: strpos(): Empty delimiter in sidebar.php on line 70
Warning: strpos(): Empty delimiter in sidebar.php on line 73
Warning: strpos(): Empty delimiter in sidebar.php on line 76
Underneath the error it has a nice form with the correct fields: country, state, city, neighborhood. It's just listing the same countries multiple times.
The delimiter for strpos() is the second parameter passed in.
In your code, you start out with:
$country_options = $state_options = $city_options = $neighborhood_options = '';
These are each the values you use as delimiters, and they are all empty - hence your error. After you perform your strpos() checks using a given key, then you set it. For instance:
$pos_country = strpos($get_row['country'], $country_options);
if($pos_country === false) {
echo $country_options .= "<option value='" . $get_row['country'] . "'>" . $get_row['country'] . "</option>";
}
I'm not sure what character you're searching for with $country_options, but you immediately append a <option></option> tag to it (which is one really long delimiter). Are you, perhaps, using the wrong variables as the characters you're searching for?
EDIT
After re-reading your question, I understand the goal you're trying to achieve (I think). You simply don't want to display the same country, state, city, or neighborhood more than once.
To accomplish this, it may be easier to keep an array of "seen" values and just check that array in each loop. Try something like this:
$countries = array();
$states = array();
$cities = array();
$neighborhoods = array();
while($get_row = mysql_fetch_assoc($rs)) {
if (!in_array($get_row['country'], $countries)) {
$country_options .= '<option value="' . $get_row['country'] . '">' . $get_row['country'] . '</option>';
$countries[] = $get_row['country'];
}
if (!in_array($get_row['state'], $states)) {
$state_options .= '<option value="' . $get_row['state'] . '">' . $get_row['state'] . '</option>';
$states[] = $get_row['state'];
}
if (!in_array($get_row['city'], $cities)) {
$city_options .= '<option value="' . $get_row['city'] . '">' . $get_row['city'] . '</option>';
$cities[] = $get_row['city'];
}
if (!in_array($get_row['neighborhood'], $neighborhoods)) {
$neighborhood_options .= '<option value="' . $get_row['neighborhood'] . '">' . $get_row['neighborhood'] . '</option>';
$neighborhoods[] = $get_row['neighborhood'];
}
}

How to put array into session?

This is assignment so not looking for anything perfectly safe and secure, just working.I have table in SQL database, I'm printing down all records, all records have unique reference number, for each row of the database I printed down I gave checkbox with value of the row's ref. number, when I submit them by "POST" everything is working and printing out:
if (!$_POST['checkbox']) {
echo "Your basket is empty.";
} else {
echo "<table border='0' id='games_table' cellspacing='1'>";
echo "<tr id='basket_table_row'>";
echo "<td colspan='3'>" . "Logged: " . $_SESSION['user'] . "</td>";
echo "<td colspan ='2'>" . "OS used on this machine: " . "<script type='text/javascript'>document.write(yourOS())</script><noscript>Computers</noscript>" . "</td>";
echo "</tr>";
echo "<tr id='basket_table_row'>";
echo "<td colspan='5'>" . "You put into the basket these games: " . "</td>";
echo "</tr>";
foreach ($_POST['checkbox'] as $value) {
$_SESSION['basket']=array($value);
$res=pg_query($conn,"select * from CSGames where refnumber='$value'");
while ($a = pg_fetch_array ($res)) {
echo "<tr id='games_table_row'>";
echo "<td>" . $a["refnumber"] . "</td>";
echo "<td>" . $a["title"] . "</td>";
echo "<td>" . $a["platform"] . "</td>";
echo "<td>" . $a["description"] . "</td>";
echo "<td>" . $a["price"] . "</td>";
echo "</tr>";
}
}
echo "</table>\n";
}
but only think which stays recorded in $_SESSION['basket'] is value of the last checkbox but I need all of them (60 or 70).
what Am I doing wrong?
You are overwriting te value of $_SESSION['basket'] at each iteration of the loop.
The last value is the only one stored.
Currently, you are only storing the last value, if you wish to store every value, you should add it like this:
$_SESSION['basket'][] = $value;
foreach($_POST['checkbox'] as $value){
$_SESSION['basket']=array($value);
}
every iteration of your loop is overwriting the value in $_SESSION['basket'], hence you only seeing the last checkbox value.
In every step of foreach, you create a new array in $_SESSION['basket'] with only one item, the current value of $value. It is corrected like this:
// ...
$_SESSION['basket'] = array();
foreach ($_POST['checkbox'] as $value) {
$_SESSION['basket'][] = $value;
// ...
}
// ...
You can directly do it like this
$_SESSION['basket'] = $_POST['checkbox'];
because the data of $_POST['checkbox'] is an array anyway.
What you are doing is looping the $_POST['checkbox'] and saving each data as array to a session.
this $_SESSION['basket'] = $_POST['checkbox'];
and
foreach ($_POST['checkbox'] as $value) {
$_SESSION['basket'][]=$value;
}
will have the same value.
What you have right only saves the last value of $_POST['checkbox']

Categories