How to List Has Same Id Data With While Loop in PHP

How can i list has same id data with while loop in PHP?

Order your results by series_id, so all the products with the same value will be together.

$stmt = $pdo->prepare("SELECT series_id, product_name
FROM yourTable
ORDER BY series_id");
$stmt->execute();

Then when displaying the results, show the Series header and start a new <ul> whenever it changes:

$last_series = null;
echo "<ul>\n";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
if ($row['series_id'] != $last_series) {
if ($last_series) {
echo "</ul></li>\n";
}
echo "<li>" . $row['series_id'] . " Series Product\n";
echo "<ul>\n";
$last_series = $row['series_id'];
}
echo "<li>" . $row['product_name'] . "</li>\n";
}
if ($last_series) {
echo "</li>\n";
}
echo "</ul>\n";

Update values inside while loop PHP with same ID

John Doe identified the problem: You were changing all the records with every statement because the WHERE clause matched them all. They all have the same productinformationID. That is why you saw the effect of only the last statement - it overrode all the previous.

To fix it, you need to add in the bits that identify the records uniquely.

$color1 = $_POST['color1'];
$count = count($color1);

for ($x = 0; $x <=$count; $x++) {

$savecolor = $color1[$x];

$stmt = $db->prepare('UPDATE productcolor SET colorName = :color WHERE productinformationID=:productinformationID AND productcolorID=:productcolorID');

$stmt->execute(array(':color' => $savecolor, ':productinformationID' =>$prodID, ':productcolorID' => $x));
}

(Note that what I have added to the code is at the end of the two long lines, so you will need to scroll to see it)

I do realise the value for :productcolorID is not exactly equal to $x. But that is best fixed by you.

--EDIT

Here is convenience function that may or may not be useful:

function fetch($query, $params=array(), $fetchMode=PDO::FETCH_ASSOC) {
global $db;

$stmt = $db->prepare($query);
if (!$stmt->execute($params))
return false;

if ($stmt->rowCount() > 1)
return $stmt;

$result = $stmt->fetch($fetchMode);

if (count($result) > 1)
return $result;

return reset($result);
}

Using that you can get the offset to :productcolorID like this:

$offset = fetch('SELECT MIN(productcolorID) FROM productcolor WHERE productinformationID=?', array($prodId));

After that, the code is pretty much the same as above. The only difference is the value for :productcolorID

$stmt = $db->prepare('UPDATE productcolor SET colorName = :color WHERE  productinformationID=:pid AND productcolorID=:cid');

$colorsCount = count($colors);
for ($i = 0; $i < $colorsCount; $i++) {
$color = $colors[$i];

$stmt->execute(array(
':color' => $color,
':pid' => $prodID,
':cid' => $offset + $i)
);
}

getting values from same id in while loop

You need to use textContent property, as tttdates[i] refer's <h3> which doesn't have value property.

vals.push(tttdates[i].textContent);

As you are using jQuery, You can use .map()

var vals = $(".tttdate<?php echo $post->ID?>").map(function(){
return this.textContent;
}).get();

Using while loop to output data of a specific id in same table row

while your question is a bit hard to follow I can tell you what you need to do, which is not a loop within a loop ( even though it is ). So because I don't care to decider you schema but I think I understand your issue, i'll outline it with psudo code

First you need to organize your data

if ($result = mysqli_query($conn, $sql)) {

$users = []; //initialize variable to store data in.

while ($row = mysqli_fetch_assoc($result)) {
if( !isset( $users['u'.$row['id']]){
$users['u'.$row['uid']] = $row; //group users by id
}
$users['u'.$row['uid']]['images'][] = $row['image'];
}
//*note you'll have to probably add u.id as uid to you select.

foreach( $users as $user ){
//... code/html for displaying user (open).
foreach( $user['images'] as $img){
//... code/html for displaying image.
}//end foreach image
//... code/html for displaying user (close).
}//end foreach user

What you wind up with for the $users array is something like this when you output it with var_export() etc.

    [ 
[ 'u10' => [
'id' => 10,
'images' => [
'{src for image1}',
'{src for image2}',
]

]

When you pull the records with the join you get a reflection of the one to many relationship users have to images. So you have the same user row for each image row. All you need to do is group them by user id, and that will make your code down stream much easier. Unless your dealing with 1000's of users it will probably have minimal impact on the time, and is well worth it to simplify the HTML structuring. The order they are returned in the sql could be causing all kinds of issues, you could start with user 1 have 10 other users then end with user 1, this way they are grouped nicely in the first loop. To group them we can rely on the fact that associative keys in PHP are unique.

I add the u{id} there because certain PHP functions have a way of resting numeric keys, that just avoids that becoming an issue. Most the time it's not needed, but it's precautionary and takes little effort, makes the array a bit easier to read and IMO a good habit.

Lastly if I recall correctly in CSS, an id of id="10" ( #10{ ..no dice.. } ) is not valid but one of id="u10" is. A bit of an explanation on that can be found here

https://css-tricks.com/ids-cannot-start-with-a-number/

Check for same rows in a while loop and put them in a separate table

You could just gather all them first in a container, using ids as your keys so that they'll be grouped together. After that, just print them accordingly:

$data = array();
while($row = $results->fetch_assoc()){
$id = $row['id'];
$name = $row['name'];
$data[$id][] = $name; // group them
}

foreach($data as $id => $values) {
// each grouped id will be printed in each table
echo '<table>';
// header
echo '<tr>';
echo '<td>ID</td>' . str_repeat("<td>$id</td>", count($values));
echo '</tr>';

echo '<tr>';
echo '<td>Name</td>';
foreach($values as $value) {
echo "<td>$value</td>";
}
echo '</tr>';

echo '</table><br/>';
}

This will work if those fields are just like that, if you need something more dynamic, you need another dimension, and instead of just pushing name, you'll need the push the entire row:

$results = $db->query('SELECT id, name, age FROM table1');

$data = array();
while($row = $results->fetch_assoc()){
$id = $row['id']; unset($row['id']);
$data[$id][] = $row; // group them
}

$fields = array('name', 'age');

foreach($data as $id => $values) {
// each grouped id will be printed in each table
echo '<table>';
// header
echo '<tr>';
echo '<td>ID</td>' . str_repeat("<td>$id</td>", count($values));
echo '</tr>';

foreach($fields as $field) {
// construct td
$temp = '';
echo "<tr><td>$field</td>";
for($i = 0; $i < count($values); $i++) {
$temp .= '<td>' . $values[$i][$field] . '</td>';
}
echo $temp; // constructed td
echo '</tr>';

}

echo '</table><br/>';
}

Stuck with the same values when looping through database rows

Based on the comments on my question, I ended up with the following code:

$users_get = mysqli_query($conn,"SELECT a.id, SUM(b.number) AS number FROM users AS a INNER JOIN users_numbers AS b ON a.id = b.userid GROUP BY a.id ASC");
$loop1 = 0;

while($users_items[] = mysqli_fetch_array($users_get){
echo "ID: ".$users_items[$loop1]['id']." - Num total: ".$users_items[$loop1]['number']."<br />";
$loop1++;
}

The echo inside the while is only for testing purposes. When I run this, it displays a nice list with all the user IDs and the sum of each users numbers.

How to loop through an array and sum values that belong to the same id with Laravel

Like the comants said, sum the quantity directly in the query and use thresult to udqate

Please don't use image of data see Why should I not upload images of code/data/errors when asking a question?

    try {
// take all the claim items that belong to the claim id passed
// CfInvoiceClaimItem is the model for the table cf_invoice_claim_items
$claimItems = CfInvoiceClaimItem::select(['cf_invoice_claim_items.*, DB::raw('SUM(tot_qty) AS sum_of_qty')'])
->where('cf_invoice_claim_items.invoice_claim_id', '=', $this->claim_id)
->get();

// loop through the claim items and for each claim Item linked to the same so_invoice_item_id sum the tot_qty and save it into the cf_so_invoice_items table with the corresponding id

// You get only 1 result drom the select query as long as you don't use `GROUP BY`

foreach($claimItems as $claimItem){
$UpdateItems = cf_so_invoice_items::where('so_invoice_id', '=', $this->claim_id)
->update(['tot_claimed' => $claimItem->sum_of_qty]);
}

Php for loop, 2 times same id, randomized

When you create the Kaart object, this creates a deck by merging two lists of the number range you pass in ( merging two ranges - range(1,$count)) and then shuffles the deck.

Then displaying the cards just means looping over the shuffled deck...

class Kaart
{
private $deck = null;

public function __construct( $count ) {
// Create list with 2xid's
$this->deck = array_merge(range(1,$count), range(1,$count));
// randomize the deck
shuffle($this->deck );
}
public function getCard()
{
// Loop over the randomized dech
foreach ( $this->deck as $card ) {
echo "<img src='img/card_back.jpg' id='{$card}'>";
}
}
}

// Create deck with 2x8 cards
$deck = new Kaart(8);
$deck->getCard();

PHP – Group output with same ID from within foreach loop

One method is to use team_id as keys in $team_totals_cq then simply add up the values as you go through the loop.

(Note: The preg_replace function strips anything that aren't numbers or .)

$team_totals_cq = [];

foreach ($results_cq as $results) {
$team_id = $results[6];

if (!empty($team_id)) {
if (!isset($team_totals_cq[$team_id])) {
$team_totals_cq[$team_id] = [
'id' => $team_id,
'team' => teamName($team_id),
'total_volume' => preg_replace("/[^0-9\.]/", '', $results[41]),
'total_closed' => $results[24],
'listings_closed' => preg_replace("/[^0-9\.]/", '', $results[22]),
'buyers_closed' => $results[23],
'total_agc' => preg_replace("/[^0-9\.]/", '', $results[29]),
'rental_agc' => preg_replace("/[^0-9\.]/", '', $results[30])
];
} else {
$team_totals_cq[$team_id]['total_volume'] += preg_replace("/[^0-9\.]/", '', $results[41]);
$team_totals_cq[$team_id]['total_closed'] += $results[24];
$team_totals_cq[$team_id]['listings_closed'] += preg_replace("/[^0-9\.]/", '', $results[22]);
$team_totals_cq[$team_id]['buyers_closed'] += $result[23];
$team_totals_cq[$team_id]['total_agc'] += preg_replace("/[^0-9\.]/", '', $results[29]);
$team_totals_cq[$team_id]['rental_agc'] += preg_replace("/[^0-9\.]/", '', $results[30]);
}
}
}


Related Topics



Leave a reply



Submit