php while and for loops to fill array not working - php

I have a Product master in which I have 2 fields, ONE is for Main Product (Field name 'Under') and SECOND is for Sub-product (Field name is 'Prod_desc)
What I want is a nested loop where I capture all codes (field name is Cylno) from transaction Table (ECR_CBDC).
I have 2 nested loops, First while loop is for PRODUCT_MASTER where based on user selection of a Main-product the sub-products are selected and SECOND loop is for collecting the codes for all sub-products.
Now the issue is it collects only 1 value as the FOR loop overwrites the previous value. Is there any other loop which can hold the previous value of each sub-product.
$p=mysql_query("SELECT * FROM PRODMAST WHERE Under='$product'");
while ($p2=mysql_fetch_assoc($p))
{
$prodesc=$p2['Prod_desc'];
$dc=mysql_query("SELECT * FROM ECR_CBDC WHERE Prod_desc='$prodesc' AND usr='$user'");
$num_rows = mysql_num_rows($dc);
$fill_from_array = array(); /* as "value"=>"option" */
for($i = 1; $i <= $num_rows; $i++)
{
$row = mysql_fetch_assoc($dc);
$fill_from_array[$row['Cylno']] = $row['Cylno'];
}
}

If I understand what you're asking - $fill_from_array only collects one row's worth - I think you need to define $fill_from_array outside of the first loop, so...
$p=mysql_query("SELECT * FROM PRODMAST WHERE Under='$product'");
$fill_from_array = array(); /* as "value"=>"option" */
while ($p2=mysql_fetch_assoc($p))
{
$prodesc=$p2['Prod_desc'];
$dc=mysql_query("SELECT * FROM ECR_CBDC WHERE Prod_desc='$prodesc' AND usr='$user'");
$num_rows = mysql_num_rows($dc);
for($i = 1; $i <= $num_rows; $i++)
{
$row = mysql_fetch_assoc($dc);
$fill_from_array[$row['Cylno']] = $row['Cylno'];
}
}
That way it's not over-writing $fill_from_array each time the while() loop loops. Is that what you mean?

Instead of emulating a join in code, use the JOIN syntax instead to reduce the number of loops and data transfer:
SELECT * FROM PRODMAST
INNER JOIN ECR_CBDC ON PRODMAST.Prod_desc=ECR_CBDC.Prod_desc AND usr='$user'
WHERE Under='$product'

Related

Create a temporary array in PHP to add to a larger array

I am trying to create a number of arrays to add to a larger array which I will then index two dimensionally (for example my_array[i][j]).
I believe I am having some type of pointing issue... I am iterating through a loop.... at the top of each iteration I instantiate a new array with the same name. When I try and view the output each item in the array appears blank.
Is there a better way for me to instantiate the "temp" arrays to fill the larger (outer) array? Really appreciate any and all help, this community has helped me through so many questions :D
$main_array = array();
for($i = 0; $i < $member_count; $i++)
{
$temp_array = array();
//preform SQL query here
$sql_get_member_transactions = 'some SQL query to go to my DB';
foreach($sql_get_member_transactions as $row)
{
//cannot get array to update here
array_push($temp_array, $row['amount']);
}
array_push($main_array, $temp_array);
}
#***FULL CODE BELOW***
$club_transactions = array();
for($i = 0; $i < $member_count; $i++)
{
#create an array for each member in the club,
#add each memeber's array to a larger array once filled with deposit amounts
#here check if member had a deposit (later we will check ALL transaction types...)
#if no deposit on that date add a zero to their array
$temp_member_transactions = array();
$temp_member = my_members[$i];
$sql_member_transactions = "SELECT * FROM Transactions WHERE Date >= '$first_t_date' AND Date <= '$last_t_date' AND RelatedClubID = 'THH'";
$sql_get_member_transactions = mysqli_query($conn, $sql_member_transactions);
//here we will get all transactions that lie within the
//event-transaction-date-window... in otherwords, the date window
//in the year where members transactions occured
foreach($sql_get_member_transactions as $row)
{
//we only want to include the transaction amount
//in the member-specific array if it belongs to that member
//otherwise see "else"
if($row['T_Owner'] == $temp_member)
{
$z = $row['T_Amount'];
}
else
{
//set to 0 so that we still account for the transaction date
$z = 0;
}
array_push($temp_member_transactions, $z);
}
array_push($club_transactions, $temp_member_transactions );

How to create unique number for each box on order

The issue is not how I am generating the number, that is working fine for a different app I have. The issue is counting the total number of boxes and iterating through a forloop that many times. Right now I am multiplying box_ct * qty_ord to get the total boxes. BTW, I am still trying to understand everything I can do with foreach and for loops, so if anyone has a better idea, Great.
CLARIFICATION: I am searching the database by order number and pulling back qty_ord, box_ct, and item_no for each. On some orders there is more than one item. So for each item I need to multiply qty_ord by box_ct = count and for that specific item I need to iterate through the loop based on what my count is.Right now if I remove the foreach and hardcode the for loop count variable it works fine. Any ideas on what is wrong with my foreach?
qty_ord | box_ct | item_no
------------------------
1 2 10001
3 3 10002
2 1 10003
2 3 10004
2 6 10005
Below is my code.
$sql ="SELECT imitmidx_sql.box_ct, oeordlin_sql.item_no, oeordlin_sql.qty_ord
FROM imitmidx_sql
JOIN oeordlin_sql ON oeordlin_sql.item_no = imitmidx_sql.item_no WHERE ord_no ='$orderNum'";
$query = odbc_exec($conn, $sql);
$row7 = odbc_fetch_array($query);
foreach($row7['item_no'] as $item){
$count = $row7['qty_ord'] * $row7['box_ct'];
for($counter = 0; $counter <= $count; $counter++){
//GRAB NUMBER FROM FILE
$sscc = file_get_contents("ucc128.txt");
//INCREMENT NUMBER
$sscc++;
//PUT THE NUMBER BACK IN FILE
$sscc = file_put_contents("ucc128.txt", $sscc);
//COMBINE STATIC NUMBER AND NUMBER FROM FILE
$ssccnumber = "00950000".$sscc;
//CREATE CHECK DIGIT MATH
$ssccnumArray = str_split((string)$ssccnumber);
$ssccstep1 = array_combine(range(1, count($ssccnumArray)), $ssccnumArray);
$ssccstep2 = 0;
$ssccstep4 = 0;
foreach($ssccnumArray as $k => $v){
if($k%2){
$ssccstep2 += (int)$v;
}else{
$ssccstep4 += (int)$v;
}
}
$ssccstep3 = (int)$ssccstep2 * 3;
$ssccstep5 = (int)$ssccstep3 + (int)$step4;
$ssccCheckDigit = (ceil($ssccstep5 / 10) * 10) - $ssccstep5;
//END CREATE CHECK DIGIT
//CONCATENATE FULL NUMBER
$sscc1 = $ssccnumber.$ssccCheckDigit;
$sql = "INSERT INTO ucc128 (sscc, ord_no) VALUES ('$sscc1' ,'$orderNum')";
#echo $sql.'<br />';
odbc_exec($connPRONUMBER, $sql);
}
}
I believe your issue may be with the following:
foreach($row7['item_no'] as $item){
$count = $row7['qty_ord'] * $row7['box_ct'];
//...
}
This should be:
foreach($row7['item_no'] as $item){
$count = $item['qty_ord'] * $item['box_ct'];
//...
}
You are grabbing data from the query results, as opposed to the current row.
My foreach was not working, so what I did instead was get the sum using my SQL query.
SELECT SUM(imitmidx_sql.box_ct * oeordlin_sql.qty_ord) AS total
FROM imitmidx_sql
JOIN oeordlin_sql ON oeordlin_sql.item_no = imitmidx_sql.item_no WHERE ord_no ='$orderNum'
I was then able to ouput it and save $row7['total'] to the variable $count.

PHP loop sum from database

$st = $this->db->prepare("SELECT * FROM invoices WHERE group_id=?");
$st->execute(array($id));
if($st->rowCount() >= 1){
foreach ($st as $row) {
$counter = $row["paymentAmount"];
$start = 1;
for($start; $start < $st->rowCount(); $start++) {
$counter = $counter + $row["paymentAmount"];
}
}
It actually print out $row["paymentAmount"] + $row["paymentAmount"] and so on, depending on how many $row["paymentAmount"] there is. But the problem is that the last output from $row["paymentAmount"] is 2500.
There is:
10000
10000
2500
And the result is: 7500
I want it to be: 22500
And if the last result is 3000 it shall be 23000. So what I simply need is this code to take every row from the database, just not the latest one.
Edit: I want it outside of the SQL query
You don't need PHP logic for something like this. The functionality is built right into SQL.
SELECT SUM(paymentAmount) FROM invoices WHERE group_id=?
You should let your database handle the sum unless you have a legitimate reason why it needs to be handled in PHP. The database is more efficient with this type of operation and you avoid a loop in PHP.
SELECT SUM(paymentAmount) AS TotalPaymentAmount FROM invoices WHERE group_id = ?
You can then change your PHP to return just one row:
$row = $st->fetch();
echo $row["TotalPaymentAmount"];
If you need to do this calculation outside of SQL, just change your loop:
if($st->rowCount() >= 1){
//init the counter to 0 before you loop through your rows
$counter = 0;
//the foreach will iterate over your result set and add the paymentAmount to $counter.
foreach ($st as $row) {
$counter += $row["paymentAmount"];
}
//echo results outside of the loop
echo $counter;
}
If you need to code this outside SQL on purpose (e.g. because you need to do further processing for each row), then I'd code this as follows:
if ($st->rowCount() >= 1) {
$counter = 0;
foreach ($st as $row) {
$counter += $row["paymentAmount"];
}
}

MySQL Recursive Get Right Nodes PHP

I have a table containing user id with left node and right node (Both are which user id). I am trying to create a function to count all the right nodes and total nodes of a particular user id in PHP.
The Code I have written till now which is always returning 0 :
function allcount($id) //Function to calculate all children count
{
$sqlz = "SELECT * FROM user_transaction_details WHERE user_id = '$id'";
$execsql = mysqli_query($conn,$sqlz);
$array = mysqli_fetch_array($execsql);
echo $sqlz;
(array_count_values($array));
$count = 0;
echo $array['l_node'];
if(!empty($array['l_node']))
{
$count += allcount($array['l_node']) +1;
}
if(!empty($array['r_node']))
{
$count += allcount($array['r_node']) +1;
}
return $count;
}
Here is the table structure :
Table Structure
Can anybody please help.
You need to pass $conn as an argument or declare it as global inside the function, because otherwise it is not available inside the function.

Php how to check for duplicate results?

Hi I'm currently querying from a database base user ids for a contest, However I want to avoid choosing duplicates in my results_array, this function getrandomspecies receives a array_result, this array results iterates 7 times. How test that I don't put duplicates in my results_array? I have gotten several duplicates.
function getrandomspecies($array_result){
//database connection
$dbn = adodbConnect();
foreach($array_result as $possible){
//query the results
$querys= "select * from taxonomic_units where tsn = $possible";
$resultss = $dbn -> Execute($querys);
while($rowss=$resultss->FetchRow()){
$id = $rowss['tsn']; //there ID
$ranksss = $rowss['rank_id']; //ranking id, I choose 220 and 230
if($ranksss == 220 || $ranksss == 230){
$prelimary_array[] = $id;
}
}
//grab random index
$index = array_rand($prelimary_array,1);
//put result id into a variable
$newspecies = $prelimary_array[$index];
//put that variable in an array
$results_array[] = $newspecies; //there is 7 newspecies/winners at the end, I dont want duplicates
}
return $results_array;
}
MySQL should be the following :
select distinct tsn, rank_id from taxonomic_units where tsn = $possible
But you should ideally use prepared statements.
what about this? You may do it with one query:
$querys= "select DISTINCT tsn from taxonomic_units where tsn IN (".implode(",",$array_result).") AND rank_id IN (220,230) ORDER BY RAND() LIMIT 7 ";
Loop your result array and if it does not exists add it. If you end up with less than 7, do your big loop again.
replace this line :
$results_array[] = $newspecies;
by:
$loop_1_more_time=0;
if (isset($results_array)){
foreach($results_array as $result){
if ($result == $new_specie){
$loop_1_more_time=1;
}
}
}
if ($loop_1_more_time == 0){
$results_array[] = $newspecies;
}
//there, if $loop_1_more_time equals 1, start again. To start again and be sure you have seven instead of 6 or less, You could replace your big first "foreach" loop with a "for" loop that depends of the count() of the $array_result, and the $array_result would be array_result[$i] instead of $possible. $i would start at 0 and increment at each end of loop. It would not be incremented if ­­$loop_1_more_time==1;.
Example :
for ($i = 0; $i < count($array_result); $i++) {
//stuff
//if ($loop_1_more_time=1;) { $i--; }
}
Why don't you try shuffling the array, and then picking the first X numbers?
That way, rather than having to check the results array for duplicates, it will never come up in the first place

Categories