Increment issue while creating a unique order number - php

I am creating order numbers like this:
ACC4_11082018_1
ACC4_11082018_2
ACC4_11082018_3
ACC4_11082018_4
ACC4_11082018_5
.
.
.
.
etc.
I am getting an issue with incrementing the last digit.
I tried the code
date_default_timezone_set('Asia/Kolkata');
$myDate = date('dmY');
$get_id=4;
$i=1;
echo $order_no='ACC'.$get_id.'_'.$myDate.'_'.$i;
$i++;
Would you help me out with this?

I have no clue where you will be using this code/logic but this will give you infinity:
date_default_timezone_set('Asia/Kolkata');
$myDate = date('dmY');
$get_id=4;
$i=0;
while( ++$i )
{
echo $order_no='ACC'.$get_id.'_'.$myDate.'_'.$i;
// echo '<br>'; // uncomment this if you want it to look normal in your browser
}
Or if infinity is not desired then:
date_default_timezone_set('Asia/Kolkata');
$myDate = date('dmY');
$get_id=4;
$i=0;
// stop after 1,000
while( ++$i <= 1000 )
{
echo $order_no='ACC'.$get_id.'_'.$myDate.'_'.$i;
// echo '<br>'; // uncomment this if you want it to look normal in your browser
}

If you really want to generate a unique order number for anything:
you have to check that order number if already exists in database or note
/* --------------------------- New order number --------------------------- */
$check_for_order = $con->query("SELECT `order_no` FROM `table` ORDER BY `id` DESC LIMIT 1");
if($check_for_order->num_rows==1){
$row=mysqli_fetch_array($check_for_order);
$previous_order = trim($row['order_no']);
$new_order = $previous_order + 1;
$insert_order_number = $con->query("INSERT INTO `table`(`order_no`) VALUES ('{$new_order}')");
}else{
$previous_order = 1;
$on_date = date("Ymdhis"); // or you can use time() instead
$new_order = $on_date.$previous_order;
$insert_order_number = $con->query("INSERT INTO `table`(`order_no`) VALUES ('{$new_order}')");
}
/* ----------------------- New Order Number here -------------------------- */
$order_no = $new_order;

Related

Is there a faster way than array_diff in PHP

I have a set of numbers from MySQL within the range 1000 0000 (8 digits) to 9 999 999 999 (10 digits). It's supposed to be consecutive, but there are missing numbers. I need to know which numbers are missing.
The range is huge. At first I was going to use PHP to do this:
//MySqli Select Query
$results = $mysqli->query("SELECT `OCLC Number` FROM `MARC Records by Number`");
$n_array = array();
while($row = $results->fetch_assoc()) {
$n_array[] = $row["OCLC Number"];
}
d($n_array);
foreach($n_array as $k => $val) {
print $val . " ";
}
/* 8 digits */
$counter = 10000000;
$master_array = array();
/* 10 digits */
while ($counter <= 9999999999 ) {
$master_array[] = $counter;
$counter++;
d($master_array);
}
d($master_array);
$missing_numbers_ar = array_diff ($master_array, $n_array);
d($missing_numbers_ar);
d() is a custom function akin to var_dump().
However, I just realized it would take tons of time for this to be done. At the 15 minute mark, $master_array is being populated with only 4000 numbers.
How can I do this in a quicker way? MySQL-only or MySQL-and-PHP solutions both welcome. If the optimal solution depends on how many numbers are missing, please let me know how so. Tq.
Your d() probably is the cause of slowness, please remove it, and make small changes in your code
while($row = $results->fetch_assoc()) {
$n_array[$row["OCLC Number"]] = 1;
}
and
$missing_numbers_ar = [];
while ($counter++ <= 9999999999 ) {
if (empty($n_array[$counter])) {
$missing_numbers_ar[] = $counter;
}
}
If the following is still slow I would be surprised. I also just noticed it is similar to #Hieu Vo's answer.
// Make sure the data is returned in order by adding
// an `ORDER BY ...` clause.
$results = $mysqli->query("SELECT `OCLC Number`
FROM `MARC Records by Number`
ORDER BY `OCLC Number`");
$n_array = array();
while($row = $results->fetch_assoc()) {
// Add the "OCLC Number" as a key to the array.
$n_array[$row["OCLC Number"]] = $row["OCLC Number"];
}
// assume the first array key is in fact correct
$i = key($n_array);
// get the last key, also assume it is not missing.
end($n_array);
$max = key($n_array);
// reset the array (should not be needed)
reset($n_array);
do {
if (! $n_array[$i]) {
echo 'Missing key:['.$i.']<br />';
// flush the data to the page as you go.
flush();
}
} while(++$i <= $max);

Query in a while loop fetching stale data

I am trying (and not succeeding) to run a while loop with a query that gets the last row in a table, uses that data then create a new row then selects the last row in the table again (which should be the row just created) then uses that data and creates a new row. This should repeat until the while loop is no longer true.
The problem I have is the while loop runs but always uses the row it selected the first time round. So the same row get inserted over and over until the while loop is false.
My question is how can I get the query to refresh when the while loop starts a new loop?
I have tried unset() but this did not work and am out of ideas. Here the while loop of my code (which is still in progress - still so much to add):-
while ($total_debt > 0) {
$get_dp_accounts_list_query = "SELECT account_id
FROM money_debt_planner
WHERE customer_id = '".$_SESSION['customer_id']."'
GROUP BY account_id";
$get_dp_accounts_list = $db->Execute($get_dp_accounts_list_query);
while (!$get_dp_accounts_list->EOF) {
$get_dp_accounts_listArray[] = array('account_id'=>$get_dp_accounts_list->fields['account_id']);
$get_dp_accounts_list->MoveNext();
}
foreach($get_dp_accounts_listArray as $acc_list) {
$get_last_dp_entry_query = "SELECT *
FROM money_debt_planner
WHERE customer_id = '".$_SESSION['customer_id']."'
AND account_id = '".$acc_list['account_id']."'
ORDER BY line_id DESC";
$get_last_dp_entry = $db->Execute($get_last_dp_entry_query);
if($get_last_dp_entry->fields['end_debt_balance'] <> 0) {
// calculate the interest this period
$accounts_balance = $get_last_dp_entry->fields['end_debt_balance'] + $get_last_dp_entry->fields['estimated_spending'];
$min_pay = $get_last_dp_entry->fields['min_pay_amount'];
$min_pay_rate = $get_last_dp_entry->fields['min_pay_rate'];
$interest_rate = $get_last_dp_entry->fields['interest_rate'];
$int_rate = $interest_rate /100;
$int_rate_a = $int_rate + 1;
$int_value_b = $accounts_balance ;
$int_value_c = ($int_rate_a * $int_value_b) - $int_value_b . ' ';
$int_value_d = $int_value_c / 12;
$statement_balance = $accounts_balance + $int_value_d;
$min_pay_rate = ($statement_balance) * $min_pay_rate / 100;
if($min_pay_rate < $min_pay) {
$new_bill_amount = $min_pay;
} else {
$new_bill_amount = $min_pay_rate;
}
if(($statement_balance) <= ($min_pay_rate) && ($statement_balance) <= $min_pay) {
$new_bill_amount = $statement_balance;
}
// next pay date
$next_due_day1 = date('d', strtotime ( $get_last_dp_entry->fields['date'] ));
$next_due_year_month1 = date('Y-m', strtotime ( $get_last_dp_entry->fields['date'] ));
$next_due_month_a_1 = strtotime ( "+ 1 month" , strtotime ( $next_due_year_month1 ) ) ;
$next_due_month_b_1 = date ( 'Y-m' , $next_due_month_a_1);
$total_days_in_this_month = date('t', strtotime($next_due_month_b_1) );
if($next_due_day1 >= $total_days_in_this_month) {
$next_due_date_a_1 = $total_days_in_this_month;
} else {
$next_due_date_a_1 = $next_due_day1;
}
$payment_date_from_account1 = $next_due_month_b_1 .'-' . $next_due_date_a_1;
$next_due1a = strtotime ( $payment_date_from_account1 ) ;
$next_due1 = date ( 'Y-m-d' , $next_due1a );
$dp_pay_date = $next_due1; // this will be 1 month from last entry
$interest_this_period = $int_value_d; // this will be interest on last end balance + est spending
$payment_this_period = $new_bill_amount; // this will be the min payment allowed including any over credit amount
$end_balance = ''; // this will be current open balance + spending + interest - payment
$sql = "INSERT INTO `money_debt_planner` (`customer_id`, `account_id`, `date`, `open_debt_balance`, `interest_rate`, `min_pay_rate`, `min_pay_amount`, `credit_limit`, `estimated_spending`, `interest_this_period`, `payment_this_period`, `end_debt_balance`)
VALUES ('".$_SESSION['customer_id']."', '".$acc_list['account_id']."', '".$dp_pay_date."', '".$get_last_dp_entry->fields['end_debt_balance']."', '".$get_last_dp_entry->fields['interest_rate']."', '".$get_last_dp_entry->fields['min_pay_rate']."', '".$get_last_dp_entry->fields['min_pay_amount']."', '".$get_last_dp_entry->fields['credit_limit']."', '".$get_last_dp_entry->fields['estimated_spending']."', '".$interest_this_period."', '".$payment_this_period."', '".$end_balance."')";
$db->Execute($sql);
} // end if balance zero
} // end account list
// to do this will be total debt balance utstanding
$total_debt = $total_debt - 1000;
}
Any help you can offer would be great :o)

PHP Count Generated Results From Loop

I have this for loop that generates 10 results:
<?php
include "dbconnect.php";
$table = "SELECT id FROM players ORDER BY RAND()* ( 1 / percentage)";
for ($i = 0; $i < 10; $i++){
$result[0] = mysql_fetch_array(mysql_query($table));
foreach ($result as $winner){
echo $winner[0] . " ";
}
}
?>
It generates a result like:
10 10 11 9 13 11 10 12 8 12
My question is how do I count the generation? For the above example it would be:
8's = 1, 9's = 1, 10's = 3, 11's = 2, 12's = 2, 13's = 1.
I basically want to count the amount of specific results generated. Sorry if i'm not making much sense.
You need to get off of MySQL functions and check out PDO or MySQLI at a minimum. But for the meat of the question:
Don't run a query, full or limited in the loop
Look at the LIMIT clause in the query
array_count_values will count the values. You can loop it and echo or whatever
Example:
$table = "SELECT id FROM players ORDER BY RAND()*(1/percentage) LIMIT 10";
$result = mysql_query($table);
while($row = mysql_fetch_array($result)) {
$winner[] = $row[0];
}
echo implode(' ', $winner);
foreach(array_count_values($winner) as $number => $count) {
$output = "$number's = $count";
}
echo implode(', ', $output);
You're existing code to make the random choice work would look like (LIMIT 1):
$table = "SELECT id FROM players ORDER BY RAND()*(1/percentage) LIMIT 1";
for($i = 0; $i < 10; $i++){
$result = mysql_fetch_array(mysql_query($table));
$winner[] = $row[0];
}
echo implode(' ', $winner);
if you check the php manual:
http://php.net/manual/en/function.mysql-query.php
then try something like this:
while ($row = mysql_fetch_assoc($table)) {
echo $row['column_name'];
echo $row['column_name'];
//.. you get the idea
}
The id is usually the first column in a database table. This is why you are just getting the id. You need to access each row in the same way you access arrays.
I should point out that the mysql library is deprecated. So you should consider using something like PDO instead.

how to set if price row is comming soon than show update soon

how to set if price row is comming soon than show update soon
how to set if price row is comming soon than show update soon
mysql
<?
//connect to database
mysql_connect('localhost','phone','pasword');
mysql_select_db('phone');
//////Displaying Data/////////////
$id=$_GET['id']; // Collecting data from query string
if(!is_numeric($id)){ // Checking data it is a number or not
echo "Data Error";
exit;
}
$result = mysql_query("SET NAMES utf8"); //the main trick
$q=mysql_query("select * from price where id=$id AND TRIM(model) IS NOT NULL");
//Adds one to the counter
mysql_query("UPDATE price SET counter = counter + 1 where id=$id ");
//Retreives the current count
$count = mysql_fetch_row(mysql_query("SELECT counter FROM price"));
$row=mysql_fetch_object($q);
echo mysql_error();
echo "<table class='hovertable'><tr><td><img src='admin/media/$row->photo' ></td></tr>";
echo "</table>";
?>
example
my rows
2000
3000
comming soon
4900
and this code is showing like this
2000
2000
3000
Warning: number_format() expects parameter 1 to be double, string given in
4900
and i want like this
2000
2000
3000
update soon
4900
how to solve this problem please help me to solve this issue
<?php if($row->price):?><tr class=\"style1\"><td width='200'><b>Price US $:</b></td><td>Price in Dollar:
<?php
function currencyExchange($amount,$baseCurrency,$quoteCurrency) {
$open = fopen("http://quote.yahoo.com/d/quotes.csv?s=$baseCurrency[0]$quoteCurrency[0]=X&f=sl1d1t1c1ohgv&e=.csv", "r");
$exchangeRate = fread($open, 2000);
fclose($open);
$exchangeRate = str_replace("\"", "", $exchangeRate);
$exchangeRate = explode(",", $exchangeRate);
$results = ($exchangeRate[1]*$amount);
$results = number_format ($results, 2);
$amount = number_format ($amount);
$timeStamp = strtotime($exchangeRate[2]);
$timeStamp = date('F d, Y', $timeStamp);
$timeStamp = "$timeStamp $exchangeRate[3]";
echo "$results\n";
}
// for additional currency ticker symbols visit: http://finance.yahoo.com/currency-converter
$usd = array('USD','US Dollars');
$INR = array('INR','Indian Rupees');
$usd = array('usd','US DOLLARS');
$b = str_replace( ',', '', $row->price );
if( is_numeric( $b ) ) {
$row->price = $b;
}
currencyExchange("$b",$INR,$usd);
?></td></tr><?php endif; ?>
Test if the amount is numeric before trying to use functions that only work for numbers.
Replace:
$results = ($exchangeRate[1]*$amount);
$results = number_format ($results, 2);
$amount = number_format ($amount);
with:
if (is_numeric($amount)) {
$results = ($exchangeRate[1]*$amount);
$results = number_format ($results, 2);
} else {
$results = 'update soon';
}
You don't need to call number_format() on $amount because you never print that value.
What about setting the column to something like 9999999999 ( which will get around numbers problem ) then testing the incoming for these numbers and if found then echo coming soon

Making an array out of variables and update its contents based on one of the variables

I have a question that pertains to gathering events from tables in a calendar program where they are separated into "events" or "repeated events". I can get all individual events perfectly well now (thanks to Chris on this site), but if they are repeating events I have to calculate it from what is given in this particular db. If I change the types or the data in the db, it will probably trash the calendar so I have to use what I have.
The variables I have sorted out so far are:
$quid2 = The IDs for today's events that are classified as repeating events (needed earlier)
$quname = The repeated event names
$qucls = The date UNIX time for the last sent reminder of events dated today
$qutype = One of these words - daily, weekly, monthly or yearly
$qudesc = A description of the event
These variables all have the same number of items and are ordered correctly between each other. (I Hope)
Below is the logic I am trying to accomplish. It are most assuredly not proper syntax but I think it is understandable; I need to figure out what the syntax and form is. I am utterly and completely new at this... so please be gentle...
It needs to be put in an array (I think)
$arr1 = some type of array($quname, $qucls, $qutype, $qudesc)
update the array...
IF $qutype($row2) = "daily", then + 1440 to it's $qucls($row[1])
IF $qutype($row2) = "weekly", then + 10080 to it's $qucls($row[1])
IF $qutype($row2) = "monthly, then + 1 month to it's $qucls($row[1])
IF $qutype($row2) = "yearly", then + 1 year to it's $qucls($row[1])
Then final product...
while ($row = mysql_fetch_array($arr1, MYSQL_NUM)) {
$UxTime = $row[1];
date_default_timezone_set('America/Denver');
$Time = date("H:i", $UxTime);
$qufinal = sprintf("Event: %s \nTime: %s \nDesc: %s \n\n", $row[0], $Time, $row[3);
}
...
This is a big learning project for me. I don't know enough PHP and mysql to make this work but I know just enough to get me in trouble. Thanks!
EDIT: adding the queries from which I made these variables:
$today = date("Ymd");
mysql_select_db($dbname);
$query1 = "SELECT cal_id, cal_name, cal_date, cal_time, cal_type, cal_description FROM webcal_entry WHERE cal_type = "M" AND cal_date != " . $today;
$wequ1 = mysql_query($query1)
while ($row = mysql_fetch_array($wequ1, MYSQL_NUM)) {
$quid1 = $row[0], $quname = $row[1], $qutime = $row[2], $qudesc = $row[3];
}
$query2 = "SELECT cal_id, cal_type, cal_ByDay FROM webcal_entry_repeats WHERE cal_id = " . $quid1;
$wer1 = mysql_query($query2)
while ($row = mysql_fetch_array($wer1, MYSQL_NUM)) {
$quid2 = $row[0] $qutype = $row[1], $qubdy = $row[2];
}
$query3 = "SELECT cal_id, cal_last_sent FROM webcal_reminders WHERE cal_id = " . $quid2;
$wer2 = mysql_query($query3)
while ($row = mysql_fetch_array($wer2, MYSQL_NUM)) {
$qucls = $row[1];
}
The syntax for arrays is as follows:
$arrayName = array($quname, $qucls, $qutype, $qudesc);
Then you can access the values by their index on the array variable:
$arrayName[0] == $quname
$arrayName[1] == $qucls
...
You can also define it as associative array:
$arrayName = array(
"quname" => $quname,
"qucls" => $qucls,
"qutype" => $qutype,
"qudesc" => $qudesc
);
Using this syntax you can access the elements by their name:
$arrayName["quname"] == $quname
$arrayName["qucls"] == $qucls
...
More reading on this: Arrays
However, you don't really need an array for what you plan to do here. Arrays are very useful if you want to store data that is structurally equal. This applies e.g. to rows in a database: They always have the same number of entries, and the columns are of the same type.
If you have just one dataset at that point of code (one event in this case), then you need no array. Of course you have several events, but as they are processed in a loop (I assume) you handle only one event at a time, and then head to the next.
So, you want to modify a variable depending on the value $qutype. To do that, you can use a switch statement:
$dateObj = date_create("#$qucls");
switch($qutype) {
case "daily":
date_add($dateObj, date_interval_create_from_date_string("1 day"));
break;
case "weekly":
date_add($dateObj, date_interval_create_from_date_string("1 week"));
break;
case "monthly":
date_add($dateObj, date_interval_create_from_date_string("1 month"));
break;
case "yearly":
date_add($dateObj, date_interval_create_from_date_string("1 year"));
break;
}
$qucls = date_format($dateObj, "U");
I don't add the number of seconds, because that would work for days and weeks- but not for months and years, as they don't have a fixed number of seconds.
If you have questions about the functions I used above you can look up their documentation on php.net.
In the code you show you must not use mysql_fetch_array.
That function is only meant for result rows you got from a call to mysql_query, but not for normal arrays.
You don't need the while loop either. All you have to do is formatting $qucls to a readable format and produce the final string:
date_default_timezone_set('America/Denver');
$Time = date("H:i", $qucls);
$qufinal = sprintf("Event: %s \nTime: %s \nDesc: %s \n\n", $quname, $Time, $qudesc);
Edit:
Like discussed in the comments here is the revised and commented code you edited in:
$today = date("Ymd");
mysql_select_db($dbname);
// You need to use single quotes at the 'M'. Using double quotes will
// end the string and thus leading to incorrect syntax
$query1 = "SELECT cal_id, cal_name, cal_date, cal_time, cal_type, cal_description FROM webcal_entry WHERE cal_type = 'M' AND cal_date != " . $today;
$wequ1 = mysql_query($query1);
// This is a counter variable which is incremented in the loop
$i = 0;
// This is the outer while loop used to gather and store the events
while ($row = mysql_fetch_array($wequ1, MYSQL_NUM)) {
// Store the results in arrays
// Statements must be seperated by a ;
$quid1[$i] = $row[0];
$quname[$i] = $row[1];
$qutime[$i] = $row[2];
$qudesc[$i] = $row[3];
$query2 = "SELECT cal_id, cal_type, cal_ByDay FROM webcal_entry_repeats WHERE cal_id = " . $quid1[$i];
$wer1 = mysql_query($query2);
// Assuming that IDs are unique this query can only return one entry. Therefore no while is
// needed, but an if statement tests if the ID actually matched a result
if ($row = mysql_fetch_array($wer1, MYSQL_NUM)) {
//$quid2[$i] = $row[0]; <- the query above ensures that $quid1[$i] == $quid2[$i]. No need to store it again
$qutype[$i] = $row[1];
$qubdy[$i] = $row[2];
}
$query3 = "SELECT cal_id, cal_last_sent FROM webcal_reminders WHERE cal_id = " . $quid1[$i];
$wer2 = mysql_query($query3);
// Same as above; If the IDs are unique then you need no loop
if ($row = mysql_fetch_array($wer2, MYSQL_NUM)) {
// The $i++ used here is the short form. As this is the last time $i is
// used in the loop it needs to be increased before the next round. You can do
// this like this or in an extra statement. This way it's evaluated and then increased
$qucls[$i++] = $row[1];
}
// End outer while loop
}
// Now go through the results. $i holds the number of entries in the arrays + 1
// Secondary counter variable and for-loop
for ($j = 0; $j < $i; $j++) {
// Adding the dates to $qucls, formatting the string, ...
// Access them like above: $qucls[$j]
// Do not increase $j manually though - the for loop does that for you already
}
Please note that this code is untested. It's syntactically correct though.
On a side note: You are currently using three different database queries to gather the data.
You can easily merge them into a single query using SQL JOINs. If you want somebody to show you how to do that, you can show them in a seperate question and ask for them to be joined into one.

Categories