foreach doesn't look like working properly in php - php

I used following code to get the total price, but it outputs value that is higher than the expected value. What would be the reason for this?
$query = " SELECT *
FROM `mytable`
WHERE `sale_id` = $id";
$result = mysql_query($query);
$item = mysql_fetch_array($result);
foreach ($item as $row) {
$total_price += $row['price'];
}
echo $total_price;

Try this,
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$total_price += $row['price'];
}
echo $total_price;

Related

Count all foreach PHP

I've got a question:
I have the following code:
foreach($_COOKIE as $key => $value) {
$sql = "SELECT * FROM producten WHERE id='$key'";
$result = mysqli_query($conn, $sql);
while($row = $result->fetch_assoc()) {
$prijs = $row['prijs'];
echo $prijs;
}
}
What I want to do is to count all the $prijs variables (int).
I tried to use count($prijs) but didn't work.
To get the count of number of time loop, you can use counter variable and to get the sum up, you can use += to sum the values in loop.
If you want to sum up only numeric values, you can use is_numeric() as well.
$i=0;
$sum=0;
while($row = $result->fetch_assoc()) {
$prijs = $row['prijs'];
$sum += $prijs;
$i++;
}
echo $i; //will give you count
echo $sum; //will give you sum
I think you've got your wording mixed up and you mean summing up the values of $prijs, in that case, use a new variable and add to it:
$sum = 0;
foreach($_COOKIE as $key => $value) {
$sql = "SELECT * FROM producten WHERE id='$key'";
$result = mysqli_query($conn, $sql);
while($row = $result->fetch_assoc()) {
$prijs = $row['prijs'];
echo $prijs;
$sum += $prijs;
}}
As per your code, $prijs will only returns single value, so when ever you are trying to count it will only gives a 1. But if you want to set all the values come up and store as an array please try $prijs[] = $row['prijs']
try
$i=0;
foreach($_COOKIE as $key => $value) {
$sql = "SELECT * FROM producten WHERE id='$key'";
$result = mysqli_query($conn, $sql);
while($row = $result->fetch_assoc()) {
$prijs = $row['prijs'];
echo $prijs;
$i++;
echo $i;
}
}
You can simplify your code as follows:
$values = array_map('mysqli_real_escape_string', array_keys($_COOKIE));
$sql = "SELECT * FROM producten WHERE id in ('".implode("','",$values."')";
$result = mysqli_query($conn, $sql);
while($row = $result->fetch_assoc()) {
$prijs = $row['prijs'];
echo $prijs;
}
echo "Total rows: ".$result->num_rows;

Php count cannot work for my notification

When I echo ''.$count.'' its display 11101101. But I want to total count like 8 or 7 etc. What is my wrong here in my code please.
I used to try $count = mysqli_num_rows($u); also but result was same.
my code:
$g = mysqli_query($dbh,"SELECT id FROM update WHERE from_id`='".$b."' OR `to_id`='".$session->id."'") or die(mysqli_error($dbh));
while ($rows = mysqli_fetch_assoc($g)) {
$ids[]= $rows['id'];
}
foreach ( $ids as $id ){
$u = mysqli_query($dbh,"SELECT id FROM updateside WHERE `id`='".$id."' AND `view` = '0'") or die(mysqli_error($dbh));
$count = mysqli_affected_rows($dbh);
while ($rows = mysqli_fetch_assoc($u)) {
$nid= $rows['id'];
}
echo ''.$count.'';
}
Assign total count to a variable something like this:
Assumes mysqli_num_rows needs query result $u as argument.
$total = 0;
foreach ( $ids as $id ){
$u = mysqli_query($dbh,"SELECT id FROM updateside WHERE `id`='".$id."' AND `view` = '0'") or die(mysqli_error($dbh));
$count = mysqli_num_rows($u);
$count = ($count == "") ? 0 : $count;
$total = $total + $count;
while ($rows = mysqli_fetch_assoc($u)) {
$nid= $rows['id'];
}
}
echo $total;
You will need to change your code a bit like this
foreach ( $ids as $id ){
$u = mysqli_query($dbh,"SELECT id FROM updateside WHERE `id`='".$id."' AND `view` = '0'") or die(mysqli_error($dbh));
while ($rows = mysqli_fetch_assoc($u)) {
$nid= $rows['id'];
}
echo mysqli_num_rows($u);
}
If you need to echo after all foreach statements use this
$count=0;
foreach ( $ids as $id ){
$u = mysqli_query($dbh,"SELECT id FROM updateside WHERE `id`='".$id."' AND `view` = '0'") or die(mysqli_error($dbh));
while ($rows = mysqli_fetch_assoc($u)) {
$nid= $rows['id'];
}
$count = $count + mysqli_num_rows($u);
}
echo $count;
I think your issue is simply formatting bug. Why use the '' here?
Try simply write:
echo $count;
you can simply use
$count=$u->num_rows;
echo $count;

retrieve from all row and display it

$query = "SELECT * FROM main";
if ($result = $db->query($query)) {
while ($row = $result->fetch_assoc()) {
$name= $row["name"];
$image = $row["image"];
}
}
then somewhere in my code I print it out using like echo $name; but I got only one result, which is the last row. I know I have to do foreach but what variable should I put?
foreach($result as $results) ? like this?
On every iteration, you reassign the values to $name and $image, causing it to show only the last value when it leaves the loop.
You can either echo them right away in the loop, or populate an array or an object with them, so they will be available later.
Example:
$data = array();
while ($row = $result->fetch_assoc()) {
$data[] = array('name'=>$row["name"], 'image'=>$row["image"]); // push into the array
}
var_dump($data); // it's all here now
And to echo the data later, one of the ways is foreach:
foreach($data as $row) {
echo "Name: ", $row['name'], "; Image: ", $row['image];
}
$query = "SELECT * FROM main";
$result = $db->query($query);
$row = $result->fetch_assoc();
foreach ($row as $rows) {
echo $rows['name'] ." ". $rows['image'];
}

PHP Iterate through a MySQL result a certain amount of times

At the moment I have this code looping through the whole results of a query:
$result = mysqli_query($con, $sql);
$data = array();
while($row = mysqli_fetch_array($result)) {
$name = $row ['name'];
$desc = $row ['description'];
$cat = $row ['category'];
$price = $row ['price'];
$quantity = $row ['quantity'];
$id = $row ['productID'];
$image = $row ['image'];
$arr = array();
$arr ["id"] = $id;
$arr ["name"] = $name;
$arr ["desc"] = $desc;
$arr ["cat"] = $cat;
$arr ["price"] = $price;
$arr ["quantity"] = $quantity;
$arr ["image"] = $image;
array_push($data, $arr);
}
echo json_encode($data);
I want to change this to only loop through a set amount of results. I have a variable further up the code called $amount which is the amount of results I would like.
I hear I should use mysql_result() and a for loop to count to $amount, but I'm not sure how my existing code will work with that set up! Suggestions please.
EDIT:
#Styphon Pointed out that I don't actually need to change my iteration code for this to be solved. Just needed to add a LIMIT to my SQL query.
$sql = "rest of query...
LIMIT $amount"; //This will limit it to whatever is $amount. Just make sure to have it on the end of your query.
$result = mysqli_query($con, $sql);
$data = array();
while($row = mysqli_fetch_array($result)) {
$arr = array();
$arr["id"] = $row['productID'];
$arr["name"] = $row['name'];
$arr["desc"] = $row['description'];
$arr["cat"] = $row['category'];
$arr["price"] = $row['price'];
$arr["quantity"] = $row['quantity'];
$arr["image"] = $row['image'];
array_push($data, $arr);
}
echo json_encode($data);
Solution is the same whether you use mysql_ or mysqli_ (but you should use mysqli or even pdo). It goes something along this lines:
$num = 0;
$amount = 10;
while ($f = mysql_fetch_array($q)) {
// your code;
$num++;
if ($num==$amount) break;
}
As you mentioned for loops, with for loop you might do something like this
for ($i=0;$i<$amount;$i++) {
$f = mysql_fetch_array($q);
//your code
}
Obviously you should adjust it to suit your needs.
SELECT * FROM tbl
LIMIT 0, $amount
This will limit your result to $amount.

error printing array when looping over it

Sorry for the relatively newbie question.
Ive been stuck the past hour trying to figure out why the array named $propname does not want to print when i loop over it. Here follows my code
$result = mysql_query("SELECT * FROM `player_info` WHERE `position` = 'THP'") or die(mysql_error()) ;
while($row = mysql_fetch_array($result)) //create arrays
{
$id[] = $row['player_id'];
$propName[] = $row['name'];
$propLastName[]= $row['surname'];
}//end while
//create variables for looping
$x = sizeof($propName);
$index = 0;
while($index < $x) //print variables
{
echo $propName[$index];
$index ++;
}
Just simplify your code
$result = mysql_query("SELECT * FROM `player_info` WHERE `position` = 'THP'") or die(mysql_error()) ;
while($row = mysql_fetch_array($result)) //create arrays
{
echo $row['name'];
}
$result = mysql_query("SELECT * FROM `player_info` WHERE `position` = 'THP'") or die(mysql_error()) ;
while($row = mysql_fetch_assoc($result)) //create arrays
{
$id = $row['player_id'];
echo $propName = $row['name'];
$propLastName = $row['surname'];
}

Categories