How to create unique number for each box on order - php

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.

Related

pHp Issue: "Waiting for localhost": Maybe infinite loop issue?

I am currently working on an elo based matchmaking system. Basically, I have a database where there are a bunch of users, each having their respective ratings.
Brief explanation of code, it chooses one user at random, and chooses another user if the second user is within +-100 difference-elo of the first user (so grandmasters don't play with bronze players). If there is no one within 100 elo, the difference-elo increments by 50 and checks again.
Problem: I created a test user that is 100 elo more than the other users to test the matchmaking system. The program works except for when the first selected player is my test user. The page never loads and it is stuck on "Waiting for localhost". I assumed this meant one of my while loops was going on infinitely, but after spending sometime editing them and trying to figure out why they might be going on infinitely, the error still persists.
<?php
include('mysql.php');
include('functions.php');
$result2 = executeQuery("SELECT * FROM images ORDER BY score DESC");
function executeQuery($query2){
$connect = mysqli_connect("localhost", "root", "password","database");
$result2 = mysqli_query($connect, $query2);
return $result2;
}
// Get random
$query="SELECT * FROM images ORDER BY RAND() LIMIT 0,1";
$result = #mysqli_query($connection, $query);
//Put random in images array
while($row = mysqli_fetch_object($result)) {
$images[] = (object) $row;
}
//Get elo of random
$elo1 = $images[0]->score;
--------------------------
//Point of Interest Below
--------------------------
//Sort database by DESC. Then go through entire database. If current row's elo is with +- difference (which right now is 100) of elo1's rating, ($elo1-100 < x < $elo1+100), then put into new array with all matchups.
//Get length of array, if length is 0 (meaning no match ups were found), increase difference by 50 and try again.
$potentialMatchup = [];
$diff = 100;
$arrayLength = count($potentialMatchup);
while ($arrayLength == 0){
$diff += 50;
while($row2 = mysqli_fetch_object($result2)){
if(($row2->score > $elo1-$diff) && ($row2->score < $elo1+$diff)){
$potentialMatchup[] = (object) $row2;
}
}
$arrayLength = count($potentialMatchup);
}
-------------------------------
//Get random index between 0 and length of array.
$randomNumber = rand(0, $arrayLength-1);
//Put match up into images array
$images[1] = (object) $potentialMatchup[$randomNumber];
//Get names of images
$nameLeft = $images[0]->filename;
$nameRight = $images[1]->filename;
//If same person, pick another random
while($nameLeft == $nameRight){
$randomNumber = rand(0, $arrayLength-1);
$images[1] = (object) $potentialMatchup[$randomNumber];
$nameRight = $images[1]->filename;
}
// Close the connection
mysqli_close($connection);
$leftName = str_replace("_", " ", $images[0]->filename);
$rightName = str_replace("_", " ", $images[1]->filename);
?>

Add a count of one in every iteration in while loop, to dynamic array key

Hi I am making a polling functionality. In the below code I am trying to get count of answers by storing the key of array $count as id of the answer and += to count how many times it was chosen as an answer.
The problem that I am having is that $count[$option_id] += 1; doesn't work. Not sure what I am doing wrong with the logic. In the database the records exist and I can confirm that query run fine and gets the result.
There are 2 answers possible per vote. For eg: lets take answer with Id 1 and 2. So, in the end, it should output something like
details: {1: 20, 2: 50}
This means that 20 people have voted for Answer 1 and 50 people for 2.
Any help will be great, Thanks
$answer_count = 0;
$count = array();
$query = "SELECT * FROM `votes` where ques_id = 55";
$stmt = $this->db_obj->query_exec($query);
while($info = mysqli_fetch_array($stmt)){
$answer_count++;
$option_id = $info['option_id'];
$count[$option_id] += 1;
}
return json_encode(array("success" => "1","total" => $answer_count,"details" => $count));

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

php while and for loops to fill array not working

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'

Repeating rows in an array and them paginating them

Lets say I have a table with 20 rows and a pagination script.
The pagination script is set to display 10 rows per page and of course it will display two pages.
The problem is that sometimes my table will have less than 20 rows, lets say 3 - so the script will display just one page with 3 entries.
I need a way to reppeat those 3 rows untill the number reachers 20, store them in an array, and than use the pagination script as normal.
Any ideeas, can it be done? Can someone put this in a code?
For those who wonder why?:) This is a problem becouse with each row i have asigned a post from my blog, and I have 20 posts which i want displayed. If for example the table which aoutoupdates with cron jobs has 17 rows, i'll have just 17 posts asociated with them. This is why i need to repreat them until 20, so i'll have all my 20 posts displayed no matter how many rows i have in the table:)
$query = "SELECT * FROM `db_table`";//PUT HERE A PROPER QUERY.
$result = mysql_result($query);
// mysql_num_rows($result) >10 WE ARE CHECKING HOW MANY LINES DO WE HAVE.
if(mysql_num_rows($result) >10){
/*...YOUR EXISTING CODES HERE...*/
}
else{
while($rows = mysql_fetch_assoc($result)){
$arrayOfRows[] = $rows; // HERE WE PULL ROWS FROM DB AND PUT IN AN ARRAY.
}
}
// NOW YOUR DB ROWS ARE IN THE ARRAY NAMED $arrayOfRows IF YOUR DB TABLE HAS LESS THEN 10 ROWS
$countRowsOfArray = count($arrayOfRows);
$rows = 20;
$dbRow=0;
for($n=0;$n<$rows;$n++){
if($dbRow > $countRowsOfArray) $dbRow = 0;
$newArrayOfRows[$n] = $arrayOfRows[$dbRow];
$dbRow++;
}
//NOW YOU HAVE $newArrayOfRows WHICH YOUR ROWS REPEATED UNTIL 20 LINES.
print_r($newArrayOfRows); //SEE IF THEY ARE THERE.
A simple solution would be (note: this code is optimized for readability, not speed):
$result = array();
for($i = 0; $i < 20; $i++){
$result = $array[$i % sizeof($array)];
}
This will fill the $result array with the contents of $array, repeating if necessary. You can also replace the loop condition by:
$i < 20 || $i < sizeof($array)
This will copy the whole array and, if necessary (the array has less than 20 entries), add copies.

Categories