No foreach Display - php

<?php
$pros_array_id= array_column($_SESSION['cart'], 'paint_id');
$productee = $productn->getData('paint');
foreach($productee as $pro):
if($pro['paint_id'] == $pros_array_id):
?>
<table>
<tr>
<td class="imgTag">
<img class="img-fluid" src="<?php echo $pro['paint_image'] ?? 1; ?>" >
</td>
</tr>
</table>
<?php
endif;
endforeach;
?>
Am trying to display session cart items and its not showing anything. When I print_r($productee) and print_r($pros_array_id) after the foreach statement both display the accurate data, yet nothing displat in the <tr> tag.
The is to display the result
When I implode $pros_array_id like this "$imp = implode(" ",$pros_array_id);" and put the variable in the if-statement, it works fine if only one product is in the session, but the moment I add more than one products in the session, nothing is display again.
Please can someone point to me what I should do?
Thanks

Try it like this:
<table>
<?php
$pros_array_id = array_column($_SESSION['cart'], 'paint_id');
$productee = $productn->getData('paint');
foreach($productee as $pro) {
//Also see and try to disable this check to see if it works then!
if($pro['paint_id'] == $pros_array_id) { ?>
<tr>
<td class="imgTag">
<img class="img-fluid" src="<?php echo $pro['paint_image'] ?? 1; ?>">
</td>
</tr>
<?php
}
}
?>
</table>
Always make sure while debugging this kind of code to eliminate any checks that could result in false, so try disabling the "if clause" as well, to see if it displays something then.

Related

How can I check if a variable is set and is the same value as another one which comes from a loop?

The thing is that I want to check if user's super variable is same as a value that I have on another variable that contains an array of values.
The problem is that the array is on 2 dimentions, so I need to loop the array before checking if it matches with the variable I am getting from the URL.
I don't want to do it with a function, but the best way of accomplishing it.
Here's the code:
<?php
$detalles = [
array("nombre"=>"Manzana", "precio"=>45.95, "color"=>"Rojo"),
array("nombre"=>"Pera", "precio"=>40.36, "color"=>"Verde"),
array("nombre"=>"Uva", "precio"=>95.21, "color"=>"Purpura"),
array("nombre"=>"Naranja", "precio"=>15.60, "color"=>"Naranja"),
array("nombre"=>"Mango", "precio"=>10.80, "color"=>"Amarillo")
];
?>
<!DOCTYPE html>
<html>
<head>
<title>Results of $_GET variable</title>
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div style="margin-top: 20px" class="container">
<table class="table table-striped">
<tr>
<td colspan="2">Product details</td>
</tr>
<?php foreach($detalles as $producto):
if(!isset($_GET['producto']) || $producto["nombre"] != $_GET['producto']){
header('Location: index.php');
}
if($producto["nombre"] == $_GET['producto']): ?>
<tr>
<td>Nombre:</td>
<td>{ <?php echo $producto["nombre"]; ?> }</td>
</tr>
<tr>
<td>Precio:</td>
<td>{ <?php echo $producto["precio"]; ?> }</td>
</tr>
<tr>
<td>Color:</td>
<td>{ <?php echo $producto["color"]; ?> }</td>
</tr>
<?php endif;
break;
endforeach; ?>
</table>
</div>
</body>
</html>
This is the details.php file, there's a file that is previous of this one which has a form with a get method and an action so everything works fine, my logic is what is not right.
Thank you in advance.
Blessings
You check in every loop if $_GET['producto'] is set. You have to check it once before the loop.
Don't print the details in your loop. First you have to find the product, and then show the details.
<?php
if( !isset($_GET['producto']) ) header("Location: index.php");
$found = null;
foreach($detalles as $producto){
if( $producto["nombre"] == $_GET['producto']){
$found = $producto;
break;
}
}
?>
<tr>
<td>Nombre:</td>
<td>{ <?php echo $found["nombre"]; ?> }</td>
</tr>
...

php loop problems

noob problem: i have some issues with a loop in php...here is the code (i used the same methodology for other pages and it works); the code it is supposed to display the names of the products from a order, it works, but it is not showing the very first product , i don't know why :
<?php $i=1; while($row_selectOrderItems = mysqli_fetch_array($result_selectOrderItems)){ ?>
<tr>
<td> <?php echo $i; ?> </td>
<td> <?php echo $row_selectOrderItems['pro_name']; ?> </td>
<td> <?php echo $row_selectOrderItems['pro_price']; ?> </td>
<td> <?php echo $row_selectOrderItems['q']; ?> </td>
<td> <?php echo $row_selectOrderItems['q']*$row_selectOrderItems['pro_price']; ?> </td>
</tr>
<?php $i++; } ?>
and here is the code where i used mysqli_fetch_array before the loop
$query_selectOrderItems = "SELECT *,order_items.quantity AS q FROM orders,order_items,products WHERE order_items.order_id='$order_id' AND order_items.pro_id=products.pro_id AND order_items.order_id=orders.order_id";
$result_selectOrderItems = mysqli_query($con,$query_selectOrderItems);
$row_selectOrderItems=mysqli_fetch_array($result_selectOrderItems);
Does anyone have any idea how should i modify this code? Thank you!
You're reading and ignoring the first record in the results. Consider how your loop works:
while($row_selectOrderItems = mysqli_fetch_array($result_selectOrderItems))
Each iteration calls mysqli_fetch_array, stores the record in $row_selectOrderItems, then uses that to display the record. Then consider what you do before the loop:
$row_selectOrderItems = mysqli_fetch_array($result_selectOrderItems);
You're doing exactly that same thing, but not displaying that first record.
Simply remove that first call to mysqli_fetch_array before the loop.
$row_selectOrderItems=mysqli_fetch_array($result_selectOrderItems);
remove this line, so that, it will not read the 1st result at starting.
Now, when you use it in the while loop, it reads the first line
may be you used mysqli_fetch_array($result_selectOrderItems) before this for loop.
check once

Image links change to an image that exists

This is a really bizarre issue that I've been having.
It happens to images that seem to have a name that is similar to something else.
For instance, if I have an image named image0001.png and I try to display an image with the source of image0010.png - which doesn't exist - then the image does not display as nothing, or fire onerror image, instead it displays as image0001.png which does exist.
I have no idea how to to fix this because I don't really know what is going on.
I am using the following code to fetch results from the database and produce a table with item details.
<?php while ($row = $retval->fetch_array()) { ?>
<tr>
<td>
<?= $row['id']; ?>
</td>
<td>{$row['name']}</td>
<td>
<a href="/path/to/item/<?= $row['id']; ?>.php">
<img src="/images/<?= $row['id']; ?>.jpg" onerror="this.src='/images/error.png';">
</a>
</td>
<td><?= $row['description']; ?></td>
</tr>
<?php } ?>
Sounds like mod_speling is enabled on your server.
Requests to documents sometimes cannot be served by the core apache server because the request was misspelled or miscapitalized. This module addresses this problem by trying to find a matching document, even after all other modules gave up.
Documentation
You can try to disable this apache module in a .htaccess file:
CheckSpelling Off
The obvious other alternative is to use file_exists, removing the reliance of JavaScript and ensuring that the image is shown if it exists or an error image if not.
<?php while ($row = $retval->fetch_array()) { ?>
<tr>
<td>
<a href='/path/to/item/<?= $row['id']; ?>.php'><?= $row['id']; ?></a>
</td>
<td>{$row['name']}</td>
<td>
<a href='/path/to/item/<?= $row['id']; ?>.php'>
<?php if (file_exists("/images/{$row['id']}.jpg")) { ?>
<img src="/images/<?= $row['id']; ?>.jpg" />
<?php } else { ?>
<img src="/images/error.png" />
<?php } ?>
</a>
</td>
<td><?= $row['description']; ?></td>
</tr>
<?php } ?>

PHP $_GET is empty trying first REST requests

trying to get my head around REST, I am following/copying a tutorial. The "$_get" is blank, I noticed that the URL that is being called is blank here is a copy,
http://localhost/RestClient/index.php?action=get_user&id=
but the href I am clicking looks ok to me.
<a href='http://localhost/RestClient/index.php?action=get_user&id='3' alt=user_'3'>Carbonnel</a>
here is my code I am new to PHP so figuring it all as I go!!!!
<?php
/*** this is the client ***/
if (isset($_GET["action"]) && isset($_GET["id"]) && $_GET["action"] == "get_user") // if the get parameter action is get_user and if the id is set, call the api to get the user information
{
$user_info = file_get_contents('http://localhost/RestServer/api.php?action=get_user&id=' . $_GET ["id"]);
$user_info = json_decode($user_info, true);
// THAT IS VERY QUICK AND DIRTY !!!!!
?>
<table>
<tr>
<td>Name: </td><td> <?php echo $user_info["last_name"] ?></td>
</tr>
<tr>
<td>First Name: </td><td> <?php echo $user_info["first_name"] ?></td>
</tr>
<tr>
<td>Age: </td><td> <?php echo $user_info["age"] ?></td>
</tr>
</table>
<a href="http://localhost/RestClient/index.php?action=get_userlist" >Return to the user list</a>
<?php
}
else // else take the user list
{
$user_list = file_get_contents('http://localhost/RestServer/api.php?action=get_user_list');
$user_list = json_decode($user_list, true);
// THAT IS VERY QUICK AND DIRTY !!!!!
?>
<ul>
<?php foreach ($user_list as $user): ?>
<li>
<?php echo "<a href='http://localhost/RestClient/index.php?action=get_user&id='".$user ['id']."' alt=user_'".$user['id']."'>"; ?><?php echo $user["name"] . "</a>"; ?>
</li>
<?php endforeach; ?>
</ul>
<?php
}
?>
The Link
<a href='http://localhost/RestClient/index.php?action=get_user&id='3' alt=user_'3'>Carbonnel</a>
is incorrect, it must be:
<a href='http://localhost/RestClient/index.php?action=get_user&id=3' alt='user_3'>Carbonnel</a>
Watch the changes in ' signs.
In you example $_GET['id'] must have been always null.
There is definitely something wrong with you <a>.
You are using single quotes for the tag attribute and then for query string parameters too.
Any program having to interpret that will have no idea where the href= actually ends.
One solution would be to use double quotes (") for the attribute and single quotes for the value (if you need those at all).
Change
<?php echo "<a href='http://localhost/RestClient/index.php?action=get_user&id='".$user ['id']."' alt=user_'".$user['id']."'>"; ?>
to
<?php echo "<a href='http://localhost/RestClient/index.php?action=get_user&id=".$user ['id']." alt=user_".$user['id']."'>"; ?>

How can I tell if the current result is the last result in PHP

I've got a new online store written in PHP and MySQL.
<div class="content-area">
<div class="page-heading">
<h1>Store</h1>
</div>
<p style="padding-top: 5px;"><strong>You are here:</strong> Home ยป Store</p>
<table border="0" cellpadding="0" cellspacing="0" width="500">
<?php
$categories=mysql_query("SELECT * FROM categories WHERE parent='0' ORDER by owner ASC, title ASC");
while($categoriesRow=mysql_fetch_array($categories)) {
$categoriesSub=mysql_query("SELECT * FROM categories WHERE parent='$categoriesRow[id]'");
?>
<tr>
<td valign="top">
<div class="product_list">
<div class="image_product">
<img alt="<?php echo $categoriesRow['title']; ?>" src="<?php echo $cls->truska(true); ?>/theme_section_image.gif" border="0" style="vertical-align: middle;" />
</div>
<div>
<h3 class="product"><?php echo $categoriesRow['title']; ?> <?php if(mysql_num_rows($categoriesSub) > 0) { ?>(<?php while($categoriesSubRow=mysql_fetch_array($categoriesSub)) { }?>)<?php } ?></h3>
</div>
</div>
</td>
</tr>
<tr>
<td class="dotted_line_blue" colspan="1">
<img src="<?php echo $cls->truska(true); ?>/theme_shim.gif" height="1" width="1" alt=" " />
</td>
</tr>
<?php
}
?>
</table>
</div>
Where my second While loop is, I need to work out what is the last result, so I can omit a comma from my while loop.
It will show as 'Lego (Lego City, Lego Starwars,)' but I want it to show as 'Lego (Lego City, Lego Starwars)'.
How can I get if the current result is the last?
You can fix this by coming at it from the other direction.
Instead of appending a comma after each result except the last, try pre-pending a comma on every result except the first.
Set up a variable called $first outside your loop, and set it to 1. Inside the loop:
if ($first == 0) {
echo ",";
} else {
$first = 0;
}
don't add the comma if it is the first result, and add it before in all the next ones.
Just build your array of results and implode it. This takes care of any counting automatically:
$comma_separated = implode(",", $array);
You shouldn't use plain mysql access, look at PDO.
Answering your question, try something like this:
$items = array();
while ($row = mysql_fetch_assoc($result)) {
$items[] = $row['foo'];
}
echo implode(', ', $items);

Categories