PHP foreach targeting specific item - php

I got a DB query that pulls out three items randomly from several categories. I want to show "Selected" if one of the items is from a specific category. Right now if one of the items is from that specific category the "Selected" is showing on all three items. How can I target the specific item only?
foreach ( $rows as $row ) {
if ($row->catid == 56) {
echo "Selected";
}

Your question isn't very clear, but I suspect you're trying to add the attribute to an option. You need to do this in the same loop that echoes the option.
foreach ($rows as $index => $row) {
$selected = $row->catid == 56 ? "SELECTED" : "";
$itemnum = $index + 1;
echo "Item $itemnum - Category $row->catid $selected | ";
}

foreach ( $rows as $row ) {
if ($row->catid == 56) {
echo "Selected";
break;
}
Not sure what u want accomplish but i guess u want to show only one selected so u need to break loop if item is found

Related

Removing an item from an array during a foreach loop

I have the following foreach being performed in PHP.
What I would like to do is instead of the $invalid_ids[] = $product_id; building and then looping around that, I would instead like to remove the entry from array that is being looped around as I'm looping around it..
For example:
If the current $product_id fails any of the test, delete the item from the $current_list array and proceed to the next iteration of the foreach loop.
I tried to do an unset($product_id) while the foreach loop header looked like this: foreach ($current_list as &$product_id) {, but the item item is still in the array.
Does anyone have any ideas on how I can go about doing this?
foreach ($current_list as $product_id) {
// Test 1 - Is the product still active?
// How to test? - Search for a product in the (only active) products table
$valid = $db->Execute("SELECT * FROM " . TABLE_PRODUCTS . " WHERE products_id = " . $product_id . " AND products_status = 1");
// Our line to check if this is okay.
if ($valid->RecordCount <= 0) { // We didn't find an active item.
$invalid_ids[] = $product_id;
}
// Test 2 - Is the product sold out?
if ($valid->fields['products_quantity'] <= 0 and STOCK_ALLOW_CHECKOUT == "false") { // We found a sold out item and it is not okay to checkout.
$invalid_ids[] = $product_id;
}
// Test 3 - Does the product have an image?
if (empty($valid->fields['products_image'])) { // Self explanatory.
$invalid_ids[] = $product_id;
}
}
$product_id isn't the actual data in the array, it's a copy of it. You would need to unset the item from $current_list.
I'm don't know how $current_list is stored, but something like unset($current_list['current_item'] would do the trick. You can use key to select the current_item key in the array.
A similar way of iterating the Array, where you can get the array key, from the PHP key docs...
while ($fruit_name = current($array)) {
if ($fruit_name == 'apple') {
echo key($array).'<br />';
}
next($array);
}
Untested, but something like this...
while ($product_id = current($current_list)) {
// Do your checks on $product_id, and if it needs deleting...
$keyToDelete = key($array);
unset($current_list[$keyToDelete]);
next($current_list);
}
I think this simple code may help you
let's say we have an array of integers and we want to remove all the items that are equal to "2" inside of the foreach loop
$array = [1,2,1,2,1,2,1];
foreach ($array as $key => $value)
{
if($value==2)
unset($array[$key]);
}
var_dump($array);
this shows the following result
array (size=4)
0 => int 1
2 => int 1
4 => int 1
6 => int 1

Outputting MySQL LEFT JOIN in PHP

I have made a mysql query like this
SELECT
forum_subcategories.name_sub,
forum_categories.id,
forum_categories.name
FROM
forum_subcategories
LEFT JOIN forum_categories ON forum_subcategories.catid = forum_categories.id
and when i echo it like this
while($row = $result->fetch_assoc()){
echo '<h3><strong>'.$row['name'].' - '.$row['id'].'</strong></h3>';
echo '<h4>'.$row['name_sub'].' - '.$row['id'].'</h4>';
I get the following result:
Category-1
subcategory belonging to 1
Category-1
subcategory belonging to 1
Category-2
subcategory belonging to 2
Category-2
subcategory belonging to 2
Category-3
subcategory belonging to 3
Category-3
subcategory belonging to 3
But the result i am looking for is this:
Category-1
subcategory belonging to 1
subcategory belonging to 1
Category-2
subcategory belonging to 2
subcategory belonging to 2
Category-3
subcategory belonging to 3
subcategory belonging to 3
How would i achieve this result?
Your query is correct as it is, this is just a matter of only sending the category as output when it has changed. Store the category in a variable, and on each loop iteration, check to see if the new value matches the old. If it does not, print it.
// variable to hold the current one...
// It starts empty.
$current_category = '';
// Remember whether there's a <div> unclosed
$subcat_div_open = false;
while($row = $result->fetch_assoc()){
// Compare to the category of the loop iteration
if ($row['name'] !== $current_category) {
// If there's a subcategory <div> open, close it
if ($subcat_div_open) {
echo '</div>';
}
echo '<h3><strong>'.$row['name'].' - '.$row['id'].'</strong></h3>';
// Store the new one to compare next time around
$current_category = $row['name'];
// Ouput an opening <div> for the subcategories
// and keep track of its state
echo '<div>';
$subcat_div_open = true;
}
// Always output the subcategory
echo '<h4>'.$row['name_sub'].' - '.$row['id'].'</h4>';
}
// Clean up the open div
if ($subcat_div_open) echo '</div>';
how about something like this?
$last_category = '';
while($row = $result->fetch_assoc()) {
$category = '<h3><strong>'.$row['name'].' - '.$row['id'].'</strong></h3>';
echo ($category == $last_category) ? '' : $category;
echo '<h4>'.$row['name_sub'].' - '.$row['id'].'</h4>';
$last_category = $category;
}

How to cross check POST with database

Hi guys I was wondering if they is a way to cross check select options getting posted to a different page with a database just to make sure that someone hasn't change anything using a inspect element or firebug or any developer tool.
database table product
my database looks something like this but they are over 400 data in it.
pid name size
1 grey 12 inch
2 blue 16 inch
database table category
pid category
1 vans
2 nike
database table itemised
pid price
1 30.00
2 50.00
item.php
in my item.php page I have a table. The size and category and SELECT OPTION then I have an input field for amount which uses jquery for validation.
in my cartpage.php
I Posting the pid, size and category then I am using all those to find the price(I AM NOT POSTING THE PRICE, I AM USING THE pid, size and category to find it.)
Now the problem is, if someone was to change the value for the size or category or both. They will still get posted but obviously the price wouldn't be find because the database can't find those value getting posted.
How I show my value category example *similar to how i show size too apart from I change the select statement*
<select id="Category" name="Category">
<?php
dbconnect();
$stmt = $conn->prepare("SELECT Name FROM Category WHERE pid=:id");
$stmt->bindParam('id',$id);
$stmt->execute();
$i = 0;
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row ) {
if ($i == 0) {
echo '<option SELECTED value="'.$row['Name'].'">'.$row['Name'].'</option>
';
}
else {
echo '<option value="'.$row['Name'].'">'.$row['Name'].'</option>';
}
$i++;
}
?>
</select>
My question
Is they a way to find out that what is getting posted exist in the database and it is related to the pid? and if not that item shouldn't be added.
Edited to add how my cart page looks like Jim Martens I have added the code you show in your answer
//I have session start on top of this page.
<?php
*jim matens your code starts here*
if (isset($_GET['pid'])){
$id = $_GET['ProdID'];
$categoryID = (isset($_POST['Category']) ? intval($_POST['Category']) : 0);
dbconnect();
$stmt1 = $conn->prepare("SELECT CatID FROM Category WHERE pid=:id");
$stmt1->bindParam('id',$id);
$stmt1->execute();
$isValid = false;
$rows2 = $stmt1->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows2 as $row1) {
if ($row1['CatID'] == $categoryID) {
$isValid = true;
break;
}
}
}
*My code starts here*
if(isset($_POST['pid']) && isset($_POST['length']) && isset($_POST['Qty']) && isset($_POST['Category'])){
$pid = $_POST['pid'];
$length = $_POST["length"];
$qty = $_POST['Qty'];
$Category = $_POST['Category'];
$wasFound = false;
$i = 0;
// If the cart session variable is not set or cart array is empty
if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) {
// RUN IF THE CART IS EMPTY OR NOT SET
$_SESSION["cart_array"] = array(0 => array("item_id" => $pid, "length" => $length, "Category" => $Category, "quantity" => $qty));
} else {
// RUN IF THE CART HAS AT LEAST ONE ITEM IN IT
foreach ($_SESSION["cart_array"]as $array_key=>$each_item) {
if ($each_item['item_id'] == $pid && $each_item['length'] == $length && $each_item['Category'] == $Category) {
$_SESSION["cart_array"][$array_key]['quantity']+=$qty;
$wasFound = true;
} // close if condition
} // close while loop
// close foreach loop
if ($wasFound == false) {
array_push($_SESSION["cart_array"], array("item_id" => $pid, "length" => $length, "Category" => $Category, "quantity" => $qty));
}
}
header('Location: '.fetchinline($bpages).$currentFile);
exit();
}
?>
I hope I have explain this clearly and if not please leave a comment and I will try and rephrase the question.
Thanks
JavaScript validation is a nice gimmick for spelling issues and the like. But it is neither foolproof nor able to actually verify if the data is semantically correct. Therefore you need to send the data to the PHP script.
That script now verifies it first for integrity (correct value type and the like). After this initial step you verify against the database in your case. If I understand you correctly, you want to make sure that the sent category is an existing category. There is one very simple way to achieve that.
First your form.
<select id="Category" name="Category">
<?php
dbconnect();
// select the ID of the category as well (should be there anyway)
$stmt = $conn->prepare("SELECT ID, Name FROM Category WHERE pid=:id");
$stmt->bindParam('id',$id);
$stmt->execute();
$i = 0;
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
if ($i == 0) { ?>
<option selected="selected" value="<?php echo $row['ID']; ?>"><?php echo $row['Name']; ?></option>
<?php } else { ?>
<option value="<?php echo $row['ID']; ?>"><?php echo $row['Name']; ?></option>
<?php
}
$i++;
}
?>
</select>
For the actual processing of the input, you read all categoryIDs from database and check if the selected ID (should be made to integer by now) is among them. If yes, everything's fine, if not the user has given invalid input.
A quick example for that:
$categoryID = (isset($_POST['Category']) ? intval($_POST['Category']) : 0);
dbconnect();
$stmt = $conn->prepare("SELECT ID FROM Category WHERE pid=:id");
$stmt->bindParam('id',$id);
$stmt->execute();
$isValid = false;
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
if ($row['ID'] == $categoryID) {
$isValid = true;
break;
}
}
ID stands here for the category ID (whatever that is in your case).
Of course your real code would continue before and after this, but it should give you the general direction.

PHP how to echo the first value of each group in a mysql query list

To better explain my situation, please take a look at this mokeup query result:
Category Item
cat1 Item 1
cat1 Item 2
cat1 Item 3
cat23 Item x
cat23 Item y
cat23 Item z
X apples
X oranges
X bananas
and so on....
I am pulling the data off a mysql database and would like to display the results like this:
Category----Item
cat1 Item 1
Item 2
Item 3
cat23 Item x
Item y
Item z
X apples
oranges
bananas
and so on....
I tried different ways but I am coming up empty. This is the latest attempt:
PHP
//Headers
echo 'Category';
echo ' | ';
echo 'Item';
echo "\n";
$sql = "SELECT `table1`.*, `table2`.* FROM table1 INNER JOIN table2 ON `table1`.`Category` = `table2`.`Category` ORDER BY `table1`.`Category`, `table2`.`Item`";
$dbq = mysql_query( $sql );
$cat = '';
while( $data = mysql_fetch_assoc( $dbq ) ) {
if( !$cat == $data['category'] ) {
$cat = $data['category'];
echo $cat;
echo ' | ';
echo $data['item'];
echo "\n";
}
else {
echo ' ';
echo ' | ';
echo $data['item'];
echo "\n";
}
}
With this code, the current output is:
Category----Item
cat1 Item 1
Item 2
Item 3
Item x
Item y
Item z
apples
oranges
bananas
...rather than the desired output.
I am looking for the most efficient and simple way to echo each category 1 time only. Perhaps this code is not the best way to approach it, but I tried in different ways and my brain right now is shut S_S .
Took me quite some time...
Change
if( !$cat == $data['category'] ) {
To
if( $cat != $data['category'] ) {
Better to concatenate the Items of same category and store it like as Item1,Item2,Item3.
When you want to use this Items use explode() to split and
when ever you want to search in this items for a particular item use mysql's FIND-IN-SET
Not sure what you're looking for as that solution seems like it solves what you need it to do but if you want to be more tolerant of the result orders you can try this:
$concated_data = array();
while( $data = mysql_fetch_assoc( $dbq ) )
{
if ( ! array_key_exists( $data['category'], $concated_data ) )
$concated_data[$data['category']] = array();
array_push($concated_data[$data['category']], $data['item']);
}
foreach ($concated_data as $category => $items)
{
echo $category;
$count = count($items);
for ($i = 0; $i < $count; $i++)
{
if ($i == 0)
echo "\t";
else
echo "\t\t";
echo $items[$i]."\n"; // Items
}
}
Formatting up to you at this point I guess but I think putting the data into an array of arrays is the best way so the top level keys are categories and then the arrays they point to now hold an array of your items. This also doesn't assume that you get results in the same category consecutively.
Sorry code might contain bugs as I haven't coded in PHP in awhile. But basically you should accumulate the items first then go through the accumulated list and output the data.

issues with php if statement within foreach loop

I did have a quick search on this but couldn't find anything relating to my problem. I'm having issues with an if statement within a foreach loop. I'm pulling a list of categories from one class, and a single category to be selected from another. The code below (with the if statement removed) works perfectly, and returns 12 options with populated values.
foreach ($user_info->categories as $key=>$category) {
$category_name = $user_info->category_names[$key];
echo '<option value="'.$category.'">'.$category_name.'</option>';
}
However when I add the if statement inside as below:
foreach ($user_info->categories as $key=>$category) {
$category_name = $user_info->category_names[$key];
if ($category = $get_article_info->category_1) {
echo '<option value="'.$category.'" selected="selected">'.$category_name.'</option>';
} else {
echo '<option value="'.$category.'">'.$category_name.'</option>';
}
}
I get a list of options with the text populated but all twelve options have value="". $get_article_info->category_1 works when echoed on it's own, and even if it were not found I would expect the if statement to echo 12 options without any selected (the same as the first code example).
You are using = instead of == You should change
if ($category = $get_article_info->category_1) {
To
if ($category == $get_article_info->category_1) {

Categories