php foreach returns last variable selected - php

the foreach doesn't seem to work correctly in which the last value selected is working but not all.
The array is selected from here:
<fieldset>
<legend>status:</legend>
<?php foreach ($statuss as $status): ?>
<div><label for="status<?php hscout($status['id']);
?>"><input type="checkbox" name="statuss1[]"
id="status<?php hscout($status['id']); ?>"
value="<?php hscout($status['id']); ?>"<?php
if ($status['selected'])
{
echo ' checked="checked"';
}
?>/><?php hscout($status['description']); ?></label></div>
<?php endforeach; ?>
</fieldset>
The index is as follows:
if (isset($_POST['statuss1']))
{
foreach ($_POST['statuss1'] as $status1)
{
$a = mysqli_real_escape_string($link, $status1);
$sql = "SELECT b FROM C WHERE d ='$a'";
$result = mysqli_query($z, $sql);
if (!$result)
{
$error = 'Still not working you.....';
include 'error.html.php';
exit();
}
$selected1s = array();
while ($row = mysqli_fetch_array($result))
{
$selected1s[] = $row['b'];
}
}
}
the $selected1s[] works only if one variable is selected. If multiple variables are selected, the last variable is parsed through.

Every time through the foreach loop that fetches the selected items, you say $selected1s = array(), which clears out the array you're using to accumulate them.
Take the line that says $selected1s = array(); and move it to before the foreach loop, if you just want to get this code working.
There's a way to build one query that gets all the rows at once, though. That typically beats the pants off doing a whole bunch of queries for one item each.
$selected1s = array();
if (!empty($_POST['statuss1'])) {
// Create a function that SQL-escapes and quotes an ID...
// (Note: requires PHP 5.3+)
$sqlify = function($id) use ($link) {
return "'" . mysqli_real_escape_string($link, $id) . "'";
};
// and apply it to the array to get back a list of SQL-ready values
$ids = array_map($sqlify, $_POST['statuss1']);
// string them together as a comma-separated list
$ids_sql = implode(',', $ids);
// and say `d IN (the list)`
$sql = "SELECT b FROM c WHERE d IN ($ids_sql)";
... do the query, fetch results into $selected1s
}
(This is the part where i'd normally advocate prepared statements and tell you to use them. Which you should, in most cases. For IN queries or the equivalent OR queries, though, they tend to suck.)

Related

'Grouping' PHP results from an MySQL query

I'm having difficulty achieving this one, so thought I'd ask..
I have a table which contains some field names. Each field entry in the table has a type, a name and an ID as per the norm.
I'd like to be able to group my SQL results so that I can 'print' each type (and the type's associated members) into a table. I tried the following:
$query = "SELECT id,type,opt_name FROM fields ORDER BY type";
$resource = $pdo->query($query);
$results = array();
while ( $row = $resource->fetch() ) {
$type[$row['type']] = $row['opt_name'];
$o_id = clean($row['id'], 'text');
$o_name = clean($row['opt_name'], 'text');
}
foreach ($type AS $o_type => $o_name) {
echo $o_type;
echo "<br>";
foreach (($type) AS $opt_name) {
echo $opt_name;
echo "<br>";
}
}
Please try not to worry too much about the HTML output, it's just for this example to show context.
When the code is executed, it will only print one row. As a result, I have 'print_r' tested both:
$type[$row['type']] = $row['opt_name'];
Which does indeed show only one row in the array. Creating:
$results = $row;
Shows all the data, but too much of it and not in the way I think will work with the 'foreach'.
I'm probably making a rookie mistake here, but can't see it.
Help!
You're going to be overwriting the value of $type['type'] instead of pushing more values onto it with:
$type[$row['type']] = $row['opt_name'];
You most likely want
$type[$row['type']][] = $row['opt_name'];
Then you'll need to fix your loop so you loop through the options, not the types twice.
foreach ($type AS $o_type => $options) {
echo $o_type;
echo "<br>";
foreach ($options AS $opt_name) {
echo $opt_name;
echo "<br>";
}
}

output one instance of a data set that could have multiple occurrences

I am having problems sifting through a MySQL query I am trying to strip. I am trying to basically take a column, pull every single entry for that column in a table and then strip it to only show one occurrence even if it happens more than once. So if the value of "bob" shows up more than once I only want it to output once, Everything I have tried either makes it so nothing outputs, or it still outputs ever occurrence of it.
My Code:
$query = mysqli_query($con,"SELECT org FROM accounts");
while ($row = mysqli_fetch_array($query)) {
$holder = array();
$validate = false;
array_push($holder, $row['org']);
for ($i=0; $i <= count($holder); $i++) {
if($holder[$i]!=$row['org']){
$validate = true;
}
}
if ($validate){
?>
<option><?php echo $row['org']?></option>
<?php
}
}
There's a php function called in_array() which lets you search through an array for a specific value without having to write your own loop. So you could replace your entire loop with something like this:
if ( ! in_array( $row['org'], $holder ) )
// your code here
However, your problem is that you're re-initialising the $holder variable to a blank array for every row. You need to store that variable outside the while loop if you wanted to use the above method. For example:
$query = mysqli_query($con,"SELECT org FROM accounts");
$holder = array();
while ($row = mysqli_fetch_array($query)) {
if ( ! in_array( $row['org'], $holder ) ) {
array_push($holder, $row['org']);
?>
<option><?php echo $row['org']?></option>
<?php
}
}
However, you can also select DISTINCT values from a MySQL query, which is probably what you want to do:
$query = mysqli_query($con,"SELECT DISTINCT org FROM accounts");
while ($row = mysqli_fetch_array($query)) {
?>
<option><?php echo $row['org']?></option>
<?php
}

PHP run query off each array variable and return results in table

I am trying to run a query off multiple array variables and display the results in a table.
The user selects 1 or more records, which includes BOL and CONTAINER. These selections are put in their own arrays and they are always an equal amount.
<?php
$bolArray = explode(',', $_POST['BOL']);
$containerArray = explode(',', $_POST['CONTAINER']);
$count = count($bolArray); // to get the total amount in the arrays
I use a FOR loop to separate each value from the 2 arrays:
for($i = 0; $i < $count; $i++)
{
$bol = $bolArray[$i];
$container = $containerArray[$i];
}
Here is the part where I'm stuck and probably where I am messing up.
I need to take each variable from the FOR loop and run query using both variables.
First, I'll start the table:
echo "<table><thead><tr><th>BOL</th><th>Container</th></thead><tbody>";
Here is where I tried a FOREACH loop:
foreach($containerArray as $container) // I am not sure if I am using this FOREACH correctly
{
And now, the query. Please take note of the variables from the first FOR loop:
$preQuery = "SELECT * FROM mainTable WHERE CONTAINER = '".$container."' AND BOL = '".$bol."'";
$preRes = mysql_query($preQuery) or die(mysql_error());
$preNum = mysql_num_rows($preRes);
I use a WHILE loop with a mysql_fetch_assoc:
while($preRow = mysql_fetch_assoc($preRes))
{
echo '<tr>'
echo '<td>'.$preRow[BOL_NUMBER].'</td>';
echo '<td>'.$preRow[CONTAINER_NUMBER].'</td>';
echo '<td>'.$preRow[ANOTHER_COLUMN].'</td>';
echo '</tr>'
}
}
echo '</tbody></table>';
?>
The query actually works. Problem is, it only returns 1 record, and it's always the last record. The user could select 4 records, but only the last record is returned in the table.
I tried to use the same query and paste it inside the first FOR loop. I echoed out the query and it displayed the same amount of times as the number of array values, but will only return data for the last record.
I do not understand what I am doing wrong. I just want to display data for each value from the array.
Edit
Here is what the code looks like when I throw the query in the first FOR loop:
echo "<table class='table table-bordered'><thead><tr><th>BOL</th><th>Container</th></tr></thead><tbody>";
for($i = 0; $i < $count; $i++)
{
$bol = $bolArray[$i];
$container = $containerArray[$i];
$preQuery = "SELECT BOL_NUMBER, CONTAINER_NUMBER FROM `intermodal_main_view` WHERE BOL_NUMBER = '". $bol ."' AND CONTAINER_NUMBER = '".$container."'";
$preRes = mysql_query($preQuery) or die();
$preNum = mysql_num_rows($preRes);
while($preRow = mysql_fetch_assoc($preRes))
{
echo '<tr>';
echo '<td>'.$preRow[BOL_NUMBER].'</td>';
echo '<td>'.$preRow[CONTAINER_NUMBER].'</td>';
echo '</tr>';
}
}
echo "</tbody></table>";
I think you can use "IN" if your POST vars are comma separated.
$preQuery = "
SELECT * FROM mainTable
WHERE CONTAINER IN ($_POST['CONTAINER'])
AND BOL IN ($_POST['BOL'])
";
$preRes = mysql_query($preQuery) or die(mysql_error());
$preNum = mysql_num_rows($preRes);
Then go to your while loop....
This would omit the need for creating an array and looping it.
Also, you need to switch to PDO for your query, and switch to parameter binding. It will take all of an hour to learn.

PHP Nested Loop. How on the second loop print items according to the id of the first loop?

I need to print a wine list from a database.
I need to print at first a categorie and after all the items that are inside. Thats the order. And i have multiple categorie. So at the end the result will be categorie1, many items, categorie2 many items...
This is the code that i write from now: I think that my problem is to print items according to the id of the alcool_categorie !!
$q_vine = "SELECT * FROM alcool_categorie ";
$r_vine = mysql_query($q_vine,$connection);
$n_vine = mysql_num_rows($r_vine);
$q_bouteille = "SELECT * FROM alcool_item where ALCNID = '$alid'";
$r_bouteille = mysql_query($q_bouteille,$connection);
$n_bouteille = mysql_num_rows($r_bouteille);
for($i = 0; $i < $n_vine; $i++){
echo mysql_result($r_vine,$i,'named').'<br/><br/>';
for($z = 0; $k < $n_bouteille; $k++){
echo mysql_result($r_bouteille,$k,'name').'<br/>';
}
}
I think it's best to use a "JOIN" in your query and then order the rows in the way you want them to be ordered, then you'll only need one loop. While running the loop you compare the category name with the previous category name and if it changes display the category name.
Example
$sql = "SELECT categoryName, bottleName FROM category INNER JOIN bottle ON category.categoryId = bottle.categoryId ORDER BY category.categoryId";
$result = mysql_query($sql,$connection);
$categoryName = ''; //just to make sure the first time the Category is named
while ($row = mysql_fetch_assoc($result)) {
if($categoryName != row['categoryName']){
$categoryName = row['categoryName'];
echo '<h1>'.$categoryName.'</h1>';
}
echo row['bottleName'].'<br/>';
}
Try this after correctly giving the category id field name in the query and inside the first while loop.
$q_vine = "SELECT id, named FROM alcool_categorie ";
$r_vine = mysql_query($q_vine,$connection);
$n_vine = mysql_num_rows($r_vine);
while ($row = mysql_fetch_assoc($r_vine)) {
$categories[$row['id']] = $row;
}
$q_bouteille = "SELECT name, ALCNID FROM alcool_item ";
$r_bouteille = mysql_query($q_bouteille,$connection);
$n_bouteille = mysql_num_rows($r_bouteille);
while ($row = mysql_fetch_assoc($r_bouteille)) {
$items[$row['ALCNID']] = $row;
}
foreach ($categories as $category_id=>$category) {
echo "<ul><li>{$category['named']}<ul>";
foreach ($items[$category_id] as $item) {
echo "<li>{$item['name']}</li>";
}
echo "</ul></li></ul>";
}
You will want to look into PHP's foreach construct. Foreach loops through an entire array of results, for each element inside the array, it extracts its value and optionally also its key. This will not require the use of mysql_num_rows.
Instead of calling mysql_result, you could use mysql_fetch_assoc to get a row's value from your mysql_query. The row's To get all values, you can incorporate this into a loop even. If you do the latter, you can create your own array of key/value pairs and use this inside a foreach construct.
Also note that the use of mysql is outdated, you will want to use mysqli now, which is very similar to mysql.

shopping cart: need to output ordered items

The other page that is the index page shows the catalog of the pizzashop. Each pizza is a hyperlink that passes the id to this page.
The core of my question is in the code that starts with the foreach loop. I would like to simply read out of the database based on the SELECT query at hand.
I know it is weird to put the query IN the loop but for now it is the only way I figured out how to loop through all the ids that are in the SESSION array.
I tried many things to output the return that the query is supposed to give, I fiddled around with the mysqli_stmt thing, all giving me numerous types of errors.
<?php
session_start();
require 'pizza_sc_fns.php';
require 'header.php';
#$pizzaId = $_GET['pizza_id'];
if (!isset($_SESSION['order']))
{
$_SESSION['order'] = array();
$_SESSION['items'] = 0;
$_SESSION['totalprice'] = 0.00;
}
if (isset ($_SESSION['order'][$pizzaId]))
{
echo $_SESSION['order'][$pizzaId]++;
echo "\$_SESSION['order'][\$pizzaId] is SET \n";
}
else
{
echo $_SESSION['order'][$pizzaId] = 1;
}
$conn = connect2db();
foreach ($_SESSION['order'] as $pizzaItem)
{
$query = "SELECT pizza_name FROM pizzas WHERE pizza_id = $pizzaItem";
$res = #$conn->query($query);
echo $res->fetch_assoc();
echo "<hr />";
//$query = mysqli_prepare($conn, "SELECT * FROM pizzas WHERE pizza_id=$pizzaItem");
//echo var_dump($query)."<br />";
//$stmt_exec = mysqli_stmt_fetch($query);
//print $pizzaItem."<br />";
}
?>
Destroy session >>
You are going to need to use a loop but you don't need to run the query for every iteration. You can use the in clause.
Your code would be something like
$query = 'Select pizza_name from pizzas where id in (';
foreach($_SESSION['order'] as $pizza_id) {
$query.= mysql_real_escape_string($pizza_id).', ';
}
$query= substr($query, 0, -2); //Get rid of the trailing comma and space
$query .= ')';
And you can run the query.
I would recommend that you use prepared statements though I'm not sure how to use them for an in statement.

Categories