I have 2 foreach with different query. The first foreach displays the customer name and transaction number.
Transaction number value in the first foreach is not from Database but from looping $no++.
How to get $no++ value from first foreach to store in second foreach based on customer name.
This Code:
$db = new mysqli("localhost","root","","test");
// Query Customer & Transaction No (First Foreach)
$sql_1 = "SELECT nama FROM pesan GROUP BY nama";
$result = $db->query($sql_1);
$no = 1;
foreach($result as $row){
echo $row['nama'].'<br>';
echo ' Transaction No ='.$no++.'<br>';
}
// Query Purchased product details (second Foreach)
$sql_2 = "SELECT product,nama FROM buy";
$result = $db->query($sql_2);
foreach($result as $row){
echo $row['nama'].'<br>';
echo 'Product Name ='.$row['product'].'<br>';
echo 'Transaction No ='.$no++.'<br>'; // transaction no is taken the value of $no++ from the foreach above based on customer name.
}
Result From First Foreach:
farez
Transaction No =1
hardy
Transaction No =2
Result From Second Foreach:
farez
Product Name = TV
Transaction No = 1
hardy
Product Name = radio
Transaction No = 2
you can actually do that in various ways;
One of them is creating an array and holding the name and transaction number in it as $name => $transaction_number form. To do this you can simply change your first foreach to:
/*----- Define Array Here ------*/
$trnoArr = array();
/*----- Define Transacrion Number And Loop through your results------*/
$no = 1;
foreach($result as $row){
/*----- Add your rows to array ------*/
$trnoArr[$row['nama']] = $no;
/*----- Echo Your results ------*/
echo $row['nama'].'<br>';
echo ' Transaction No ='.$no.'<br>';
/*----- Increase Number Value ------*/
$no++;
}
Than in your second loop you can simply get the transaction number from freshly created array like:
foreach($result as $row){
echo $row['nama'].'<br>';
echo 'Product Name ='.$row['product'].'<br>';
echo 'Transaction No ='.$trnoArr[$row['nama']].'<br>'; // Like here
}
Related
Context: I have an ordering form, that has a html select and a number input. so a user selects the item and enter the amount they want of that item, these are sent as arrays to the hander page. $_POST['item']; is an array of id's that I want to select product info from the database with. $amount = $_POST['amount']; is just an array of the amounts of each item.
Problem: Each row is being duplicated by the amount of rows there are, so in this case it's returning three rows, but duplicating each one, three times.
Objective: All I'm trying to do is foreach $_POST['item'] get that rows data from the database and show them and the respective amounts in a table, so the user can confirm the order.
handle.php
<?php
$item = $_POST['item']; // array of product ids to select data from db
$amount = $_POST['amount']; // array of amounts of each product the user ordered
$note = $_POST['note'];
$i = 0;
$each = implode(',',$item);
$stmt = $dbh->query('SELECT *
FROM `products`
WHERE `id` IN (' . $each . ')');
<table class="table">
<thead>
<tr>
<th scope="col">Item</th>
<th scope="col">Quantity</th>
<th scope="col">Price</th>
</tr>
</thead>
<tbody>
<?php
while ($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
$product_id = $row['id'];
$product_name = $row['name'];
$product_price = $row['price'];
$row['quantity'] = $amount[$row['id']];
print "<pre>";
print_r($row);
print "</pre>";
?>
<tr>
<td><?php echo $product_name;?></td>
<td><?php echo $row['quantity'];?></td>
<td><?php echo $product_price;?></td>
</tr>
<?php } ?>
</tbody>
</table>
I'm not really sure what you're trying to do, but you are reassigning
$key = array() ;
immediately after your
foreach ($amount as $key)
That's causing your
<td><?php echo $key;?></td>
to try to echo an array because you overwrote the value of $key assigned by the foreach.
Your post does not detail what data is getting duplicated so I can't really address that in this answer.
You are duplicating the same three rows because you are setting
$new = array_combine($item, $amount);
Then your SQL is grabbing the rows
$stmt = $dbh->query('SELECT *
FROM `products`
WHERE `id` IN (' . $each . ')');
Then you're looping over the same items with
foreach ($new as $key => $val) {
If you want to display the items you found in the SQL then you shouldn't have the
foreach ($new as $key => $val) {
inside your while() loop. Your while() is already looping over the rows returned for those items. This assumes you only have one product per item number.
If you expect one or more 'products' to be returned for each item number then you should be executing your SQL while looping through foreach($new), but that doesn't appear to be what the top part of your code is doing.
After some back and forth we've identified the issue: the amounts need to be tied to the item numbers.
You are getting items numbers and quantities as arrays from your HTML. So you need to loop through the items and associate them with your quantities.
// where your qualities will live
$quantities = array() ;
// loop through the array of items you received and match them up with their quantity
foreach($item as $k=>$id) {
$quantities[$id] = $amount[$k] ;
}
Then you can access the quantity in your while loop using:
$row['quantity'] = $quantities[$row['id']] ;
$query = "select * from tableitem";
$result = mysql_query($query);
$col = array();
while ($row = mysql_fetch_array($result)){
//they have computation here inside loop.
$amount = $value;
if($row['status']>3){ // base on the status only
if($amount>0){ //base on the computation
$count = $item;
// i need to count here the item before the grouping of duplicate item below.
if (!isset($col[$row['item']])) { // this is working for grouping the duplicate value
echo $row['item'];
echo $count; // count item
$col[$row['item']] = true;
}
}
}}
Sample output should be like this inside while loop if possible.
Item one 2
Item two 3
Item five 4
You can do that with sql not necessary php;
SELECT COUNT(*) as N,item
FROM tableitem
GROUP BY item
it will return duplicate items and you can check with n>1. And you can add more column for group.
$itemArray;
while ($row = mysql_fetch_array($result)){
if($row['n']>1){
itemArray[] = $row['item'];
}
}
print_r($itemArray);
If you increment array values using the keys you are trying to count:
$check = array();
foreach($values as $key => $value) {
if (isset($check[$key])) {
$check[$key]++;
} else {
$check[$key]=1;
}
}
var_dump($check);
I'm so tired of finding out why the code is not loop with foreach in place. 1st loop is fetching the person name from db I use while loop as usual and it works. 2nd loop I test the total action each one of them doing in a month so I use a foreach loop for each month. But the problem is here. I can't make it loop again because of no clue.
Here's my codes:
error_reporting(E_ALL);
$thisYear=intval(date("Y"));
for($i=1;$i<13;$i++){
$i=sprintf("%02d",$i);
$monArr[]=$i;
}
//select all team members
$sql_sTeam=mysqli_query($con,"select * from TEAMNAMES order by fname asc");
$result=array();
while($rec_sTeam=mysqli_fetch_array($sql_sTeam)){
$rows['name']=$rec_sTeam['sale_fname'];//sale name
foreach($monArr as $key=>$val){
//$rows['data'][]=(int)$key;
$mon=intval($val);
//n action each member\
$sql_mLog=mysqli_query($con,"select * from mail_log where mlog_sid='$rec_sTeam[imap_sid]' and year(mlog_dtime)='$thisYear' and month(mlog_dtime)='$mon'");
$num_mLog=mysqli_num_rows($sql_mLog);
$rows['data'][] =(int)$num_mLog;//(int) will remove double qoutes around numbers
}//foreach
array_push($result,$rows);
}//while
echo json_encode($result);
There're 4 people in TEAMNAMES but this is the only result from json_encode:
[{"name":"Ar-eshah","data":[0,0,0,0,0,0,6,0,0,0,0,0]}]
Please point me out of here coz I'm stuck for several hours.
Regards,
Here the solution that you are looking for:
error_reporting(E_ALL);
$thisYear = intval(date("Y"));
for($i = 1; $i < 13; $i++){
$i = sprintf("%02d",$i);
$monArr[] = $i;
}
//select all team members
$sql_sTeam = mysqli_query($con,"select * from TEAMNAMES order by fname asc");
$result=array();
while($rec_sTeam=mysqli_fetch_array($sql_sTeam)){
$row = array();
$row['name']=$rec_sTeam['sale_fname'];//sale name
$row['data'] = array();
foreach($monArr as $key=>$val){
$mon=intval($val);
//n action each member\
$sql_mLog=mysqli_query($con,"select * from mail_log where mlog_sid='$rec_sTeam[imap_sid]' and year(mlog_dtime)='$thisYear' and month(mlog_dtime)='$mon'");
$num_mLog=mysqli_num_rows($sql_mLog);
$row['data'][] =(int)$num_mLog;//(int) will remove double qoutes around numbers
}//foreach
$result[] = $row;
}//while
echo json_encode($result)
Any MySQL errors? In this line:
$sql_mLog=mysqli_query($con,"select * from mail_log
where mlog_sid='$rec_sTeam[imap_sid]' and
year(mlog_dtime)='$thisYear' and month(mlog_dtime)='$mon'");
You need to brake the string in order to add an array value or use curly braces... like this:
$sql_mLog=mysqli_query($con,"select * from mail_log
where mlog_sid='".$rec_sTeam[imap_sid]."' and
year(mlog_dtime)='$thisYear' and month(mlog_dtime)='$mon'");
OR
$sql_mLog=mysqli_query($con,"select * from mail_log
where mlog_sid='{$rec_sTeam[imap_sid]}' and
year(mlog_dtime)='{$thisYear}' and month(mlog_dtime)='{$mon}' ");
An example:
$a = array("name"=>"predte4a");
echo "My name is: $a['name']";
// will echo My name is array()['name']
echo "My name is: {$a['name']}";
//will echo My name is predte4a
And do not forget the quotes in your associative array keys
I have this array:
$cust = xtc_db_query("SELECT customers_id FROM orders");
$customers = xtc_db_fetch_array($cust);
When I try to display every single record I get only the first one:
foreach ($customers as $v) {
echo "ID: $v.\n <br>";
}
I tried setting the array manually and then it works fine:
$customers = array(1, 2, 3, 17);
Your $customers array will only ever contain one value (the last result from the query). You'll need to use a while loop:
$cust = xtc_db_query("SELECT customers_id FROM orders");
while($customers = xtc_db_fetch_array($cust))
{
// Use $customers here.
}
$cust = xtc_db_query("SELECT customers_id FROM orders");
while($customers = xtc_db_fetch_array($cust)){
echo "ID: $customers[customers_id].\n <br>";
}
xtc_db_fetch_array will return one record in every iteration.
To get all the records, you'll have to put xtc_db_fetch_array($cust) in while loop like below.
$cust = xtc_db_query("SELECT customers_id FROM orders");
while($customers = xtc_db_fetch_array($cust)){
print_r($customers);
}
I'm querying the database first to get all records associated with a certain userid, then i need to go in and modify the array, because one of the fields is an id and i need the name associated with that id.
So i use columnCount to iterate through the resulting array at the index of the id and replace it with the right name, which works fine, for the first six results. columnCount only returns 6, but those first six are renamed as they should be. But outside of that it takes the results from that pdostatement and populates the table normally, with all the relevant data, 17 rows right now.
Why is it returning 6, or what am i doing to get that wrong columncount?
global $__CMS_CONN__;
$timeqry = 'SELECT facility_id, program, date, visit_length, mileage, served FROM timesheet_db WHERE volunteer_id = '.$_SESSION['user_id'];
$stmt = $__CMS_CONN__->prepare($timeqry);
$stmt->execute();
$columns = $stmt->columnCount();
print $columns;
if($stmt)
{
$arrValues = $stmt->fetchAll(PDO::FETCH_ASSOC);
for($x=0;$x<$stmt->columnCount();$x++)
{
global $__CMS_CONN__;
$qry = 'SELECT facility FROM facility_db WHERE id = '.$arrValues[$x]['facility_id'];
$stmt1 = $__CMS_CONN__->prepare($qry);
$stmt1->execute();
if($stmt1)
{
$facilityName = $stmt1->fetchAll(PDO::FETCH_ASSOC);
foreach ($facilityName as $item)
{
foreach ($item as $key => $val)
{
$arrValues[$x]['facility_id'] = $val;
}
}
}
}
print "<table style=\"font-size:90%\">\n";
print "<tr>\n";
print "<th style=\"width:100%\">Facility</th>";
print "<th>Program</th>";
print "<th>Date</th>";
print "<th>Visit Length</th>";
print "<th>Mileage</th>";
print "<th>Served</th>";
print "</tr>";
foreach ($arrValues as $row)
{
print "<tr>";
foreach ($row as $key => $val)
{
print "<td>$val</td>";
}
print "</tr>\n";
}
print "</table>\n";
}
You asked for six columns in your first SELECT query:
SELECT facility_id, program, date, visit_length, mileage, served FROM timesheet_db WHERE volunteer_id = $_SESSION['user_id']
So, naturally, columnCount() is 6. It doesn't multiply the column count by the number of rows returned or anything like that.
If you want the number of rows, you need count($arrValues) (the manual says database behavior with rowCount() is inconsistent regarding SELECTs).