order number auto create based on previous number - php

What I want to do is create an automatic order number. So like this date-number of order
So the first order of today would be
20190719-01
second-order of today would be
20190719-02
etc.
Then tomorrow it needs to be like 20190720-01 20190720-02 etc and so on.
How can I achieve this? preferably in PHP

str_pad() is your friend here.
$range = range(1,10);
$period = new DatePeriod(
new DateTime('2019-07-17'),
new DateInterval('P1D'),
new DateTime('2019-07-20')
);
foreach ($period as $key => $value) {
foreach($range as $inc){
$seq = str_pad($inc,2,"0",STR_PAD_LEFT);
$order_number = $value->format('Ymd').'-'.$seq;
echo $order_number.PHP_EOL;
}
echo PHP_EOL."===========".PHP_EOL;
}
WORKING DEMO: https://3v4l.org/R5POt

Normally order numbers would be sequential, and can therefore easily be derived from the AUTO INCREMENT field. In your case this is not so easy.
You could start by getting the highest AUTO INCREMENT field from the database for all orders before today:
SELECT MAX(id) FROM orders WHERE DATE(orderDate) < CURDATE();
Let us call this id $offsetId. If no orders exist yet it should be zero.
Then first insert the order information into the database, so you can get the id of that order. You can do this either with $con->insert_id in MySQLi or lastInsertId() in PDO. let's call this the $orderId.
The reason, to use a database in this way, is to prevent that two orders ever get the same order number.
Now you can compute the order number for today:
$orderNumber = date("Ymd") . "-" . sprintf('%02d', $orderId - $offsetId);
And you can store this in the database, with the order.
You should probably anticipate more than 99 orders a day...

Related

How to use break or contnue

I have an array of admission and each student has multiple entry of payment.
Like Admission=[1,2,3,4,5,6] this is admission ids,
and Payment=[[1->1,5,6,2],[2->2,3],[3->4,7,8] this is admission id->payment_ids
foreach($admission as $a)
{
$payment=DB::table('payement')->where('admission_id',$a->admission_id)->get();
foreach($payment as $p)
{
// Here i wan if payment_date <= today_date
// 1. Add all payment
// 2. Else Go to the next admission id
}
}
It sounds like you're looking for something like this:
foreach($admission as $a)
{
$payment = DB::table('payment')->where('admission_id', $a->admission_id)->get();
$totalPayment = 0;
foreach($payment as $p)
{
if (\Carbon\Carbon::parse($p->payment_date)->lessThanOrEqualTo(\Carbon\Carbon::now())) {
$totalPayment += $p->amount;
}
}
}
Inside of the foreach loop on $payment the code above uses Carbon to compare the dates. It looks like you're using Laravel's Eloquent so you should have Carbon available in your application since it's a Laravel dependency. I use Carbon to compare the dates because it knows more about dates than I do.
Next, if it's true that payment_date is less than or equal to the current date then it will add it to the $totalPayment for that admission. Otherwise, it will move onto the next payment. This presumably makes using continue or break unnecessary unless I am misunderstanding something.
I'm not sure what you want to do with $totalPayment. Right now it will be calculated for each admission and then lost.
If you want to find the total payment across all admissions you should move $totalPayment = 0 to the line above foreach($admission as $a).
If you want to find the total payment for each admission you could set a totalPayment on each admission $a->total_payment = $totalPayment. I would then change $totalPayment = 0 to $a->total_payment = 0 and change $totalPayment += $p->amount to $a->totalPayment += $p->amount.

Calculating time difference between two db values for multiple rows

I have a database which holds two timestamps (date_ticket_reported, date_ticket_resolved), I want to caluclate the average time difference between these times for each resolved_by user_id.
Each row has a (resolved_by) column which corresponds to a user_id.
There will be multiple rows, for each user_id.
I have tried various approaches including the following.
ticket_model.php code
public function get_resolved_time_by_user($user_id){
$query1 = $this->db->select('resolved_date')->from('tickets')->where('resolved_by',$user_id)->get();
$resolved1 = $query1->row();
$query2 = $this->db->select('ticket_date_reported')->from('tickets')->where('resolved_by',$user_id)->get();
$reported1 = $query2->row();
$resolved2 = $resolved1->resolved_date;
$reported2 = $reported1->ticket_date_reported;
foreach($resolved2 as $row){
//Convert them to timestamps
$reported_dateTimestamp = strtotime($resolved2);
$resolved_dateTimestamp = strtotime($reported2);
$diff = $resolved_dateTimestamp - $reported_dateTimestamp;
return $diff;
}
}
Ticket view code
<p> Average Resolve Times <?php echo $this->ticket_model->get_resolved_time_by_user($user_id); ?> </p>
So to summarise; I want to display the average time between date_ticket_reported, date_ticket_resolved. For each user_id specified.
Any help would be awesome!
I have tried Malkhazi Dartsmelidze answer,
$this->db->query("SELECT
AVG(TIMESTAMPDIFF(SECOND, resolved_date, ticket_date_reported)) as timediff,
resolved_by as user
FROM tickets
GROUP BY resolved_by");
I get an error saying Object of class CI_DB_mysqli_result could not be converted to string
Where you say resolved_by as user. Should "user" be the user_id? ie should it say "resolved_by as user_id"?
You Can run only One Query With Myqsl:
SELECT
AVG(TIMESTAMPDIFF(SECOND, resolved_date, ticket_date_reported)) as timediff,
resolved_by as user
FROM tickets
GROUP BY resolved_by
This returns Average Time Difference in Seconds for Each User
Try this
$resolved2 = $resolved1->resolved_date;
$reported2 = $reported1->ticket_date_reported;
$diff = $resolved2 - $reported;
And then echo $diff and check what you are getting in $diff,

Compare a value to each row in the database table

Already solved. I just used WHERE MONTH(due_date) = $month in the SQL clause. Never knew it would just be like that. Thank you for all your answer!
We have a table called bills. We do not delete a bill even if it is paid already for record purposes.
So our goal is to only display The Bills for this Month. I have a $cur_month = current month value. I know how to extract the month value from a field using MONTH(), using a loop to run though the table, but when I try to echo MONTH(date) the value through out the displayed series is just the MONTH VALUE of the very first row. It seems it failed to get the MONTH VALUE of the other rows.
Fixed code below
$query = "SELECT * FROM bill WHERE MONTH(due_date)=$month";
$bresult = mysql_query($query);
while($brow = mysql_fetch_array($bresult, MYSQL_ASSOC))
{
$bdata = mysql_fetch_assoc(mysql_query("SELECT MONTH(due_date) AS M FROM `bill`"));
if($bdata['M'] == $month)
{
echo "<tr>";
echo "<td>".$brow['room_id']."</td>";
echo "<td>".$brow['tenant_id']."</td>";
echo "<td>".$brow['due_date']."</td>";
echo "</tr>";
}
}
$month there is the holder of the current month
$bdata['M'] there is the holder of the month extracted. We just displayed it to check.
So if extracted_month is equls to current_month then display bill
I hope you can help me in this.
PS: Still an amateur. This is not yet an online website. We only need help for the purpose of having it work.
1) Use a WHERE statement in your first SQL to only fetch those rows from the table.
Like this:
$query = "SELECT *, MONTH(due_date) as M FROM bill WHERE MONTH(due_date)=" . $month;
$bresult = mysql_query($query);
while($brow = mysql_fetch_array($bresult, MYSQL_ASSOC)) {
echo "<tr>";
echo "<td>".$brow['M']."</td>";
echo "<td>".$brow['tenant_id']."</td>";
echo "<td>".$brow['due_date']."</td>";
echo "</tr>";
}
2) I find it good practice to always check if the result object is created and if so, to check if it returned matches (with mysql_num_rows($result)). That way you can show an error if something goes wrong (most likely in the SQL statement) or show the user that there are no matches (bills in this case).
3) Try to use MYSQLI to connect to your database instead of MYSQL, since the latter is deprecated. (See: http://php.net/manual/en/mysqli-result.fetch-assoc.php for an example.)
Try solving this problem using SQL.
SELECT b.amount_paid
FROM bills b
WHERE MONTH(b.due_date) = 3
Using the result of this query you would have all of the amounts for this month. Sum your result and you are done.

I need some help creating a query and a database table to retroactively assign numbers to existing table

As my info states, I inherited the job of statistician for a local dart league. (Woohoo $20 a season)
I would love to implement an ELO rating system.
The current database table has over 100,000 entries.
There are 3 different games that are played. Singles, Doubles, and Team.
The originator of the database has the games entered as such:
Index Player1_num Player2_num Opp_Player1_num Odd_Player2_num H_team V_team Season Week W L Game_type
A singles game is entered twice.
values(1,20,null,30,null,200,300,11,2,1,0,301_singles)
and
values(2,30,null,20,null,200,300,11,2,0,1,301_singles)
It was done this way to facilitate easier look-ups of individuals.
A doubles game would have values such as
(3,20,21,30,31,200,300,11,2,1,0,501_doubles)
(4,21,20,30,31,200,300,11,2,1,0,501_doubles)
(5,30,31,20,21,200,300,11,2,0,1,501_doubles)
(6,31,30,20,21,200,300,11,2,0,1,501_doubles)
There again, it is built for easier queries for looking up wins and losses across seasons and with different partners.
A team game is:
(7,null,null,null,null,200,300,11,2,1,0,team_game)
So I added a match_num column to the table to help lump the games under 1 number.
However, I am unsure how best to assign the numbers, understandably, I don't feel like going through all 90k entries by hand.
Note: The early seasons were modified by hand and not all double matches have 4 entries (some only have 1). Some matches may be out of order as well (Instead of indexes: 1,2 they could be 1,9).
I don't know if you need more info for this, and I am unsure of how to post larger examples of the table.
Current code:
<body>
<?php
include "inc.php";
// Select Max Match Number
$sqlMatch="select max(match_num) from stats_results";
$match =mysql_query($sqlMatch);
$m= $match ? mysql_result($match,0):mysql_error();
$matchno= $m+1; // First Match number
$game=array("'301_singles'","'cricket_singles'","'501_singles'","'301_doubles'","'cricket_doubles'");
// selects max season
$sqlSeason="select max(season_index) from stats_season";
$season =mysql_query($sqlSeason);
$smax= $season ? mysql_result($season,0):mysql_error();
# $smax=2;
// for each season up to max season
for($s=1;$s<=$smax;$s++)
{
// Selects max week within the current season
$sqlWeek="select max(week) from stats_results where season=$s ";
$Week =mysql_query($sqlWeek);
$wmax= $Week ? mysql_result($Week,0):mysql_error();
# $wmax=2;
// for each week within current season up to the max week
for ($w=1;$w<=$wmax;$w++)
{
// each singles game
foreach($game as $g)
{
###########################################################################################################
$result = mysql_query("SELECT * FROM stats_results where season=$s and week=$w and game_code=$g ;") or die(mysql_error());
// Put them in array
for($i = 0; $rows[$i] = mysql_fetch_assoc($result); $i++) ;
// Delete last empty one
array_pop($rows);
//******************************************************
$matches=array();
foreach($rows as $record)
{
// Get a unique match code for this match
$matchid= getMatchID($record);
// Have we seen this ID before? If yes add this record index to the existing array
// otherwise create an array with just this value
if (!isset($matches[$matchid])) $matches[$matchid]= array($record['index_results']); // No
else $matches[$matchid][]= $record['index_results']; // Yes, add this Index
}
// Now $matches is an array of arrays of Index values, grouped by "match" so...
/* Sort $matches by key (see getMatchID for why!) */
ksort($matches);
// Update the table
foreach($matches as $match)
{
// Create SQL instruction to set the match_num for all the Index values in each entry
$sql= "UPDATE stats_results SET match_num = $matchno WHERE index_results IN (".implode(",", $match).")";
echo "<br>";
echo $sql;
/* Execute the SQL using your chosen method! */
// Move the match count on
$matchno++;
}
// End our loops
}
}
}
function getMatchID($gamerecord)
{
$index= "{$gamerecord['season']}-{$gamerecord['week']}-{$gamerecord['game_code']}-";
$players= array(
$gamerecord['player1_num'],
empty($gamerecord['player2_num'])?0:$gamerecord['player2_num'],
$gamerecord['opp_player1_num'],
empty($gamerecord['opp_player2_num'])?0:$gamerecord['opp_player2_num']
);
// Sort the players to get them in a consistent order
sort($players);
// Add the sorted players to the index
$index.= implode('-', $players);
return $index;
}
?>
</body>
(I'm putting this into an Answer so I can get it to layout a bit better - but it's not really a "solution" as such!)
I think what I'd do is try and build an array of arrays of Index values grouped by game - you can then use that to create SQL to update the table.
So, if $rows is an array of all records we'd do something like the following pseudo-code:
$matches= array();
foreach($rows as $record)
{
// Get a unique match code for this match
$matchid= getMatchID($record);
// Have we seen this ID before? If yes add this record index to the existing array
// otherwise create an array with just this value
if (!isset($matches[$matchid])) $matches[$matchid]= array($record['Index']); // No
else $matches[$matchid][]= $record['Index']; // Yes, add this Index
}
// Now $matches is an array of arrays of Index values, grouped by "match" so...
/* Sort $matches by key (see getMatchID for why!) */
ksort($matches);
// Update the table
$matchno= 1; // First Match number
foreach($matches as $match)
{
// Create SQL instruction to set the match_num for all the Index values in each entry
$sql= "UPDATE games SET match_num = $matchno WHERE Index IN (".implode(",", $match).")";
/* Execute the SQL using your chosen method! */
// Move the match count on
$matchno++;
}
So all that leaves is the getMatchID function - if we give each match a temporary ID based on it's season, week and a sorted list of it's participants (and use the Season and Week first) that should be unique for each game and we can sort by this index later to get the games in the right order. So again in rough pseudo-code, something like:
function getMatchID($gamerecord)
{
$index= "{$gamerecord['Season']}-{$gamerecord['Week']}-{$gamerecord['H_Team']}-{$gamerecord['V_Team']}-";
$players= array(
empty($gamerecord['Player1_Num'])?0:$gamerecord['Player1_Num'],
empty($gamerecord['Player2_Num'])?0:$gamerecord['Player2_Num'],
empty($gamerecord['Opp_Player1_Num'])?0:$gamerecord['Opp_Player1_Num'],
empty($gamerecord['Opp_Player2_Num'])?0:$gamerecord['Opp_Player2_Num']
);
// Sort the players to get them in a consistent order
sort($players);
// Add the sorted players to the index
$index.= implode('-', $players);
return $index;
}
So all being well $index would come back with something like 11-2-200-300-0-0-20-30 for the first singles match in your example - no matter which of the game records we were looking at.
Does that make sense/help at all?

additional results/note in search

wondering if it is possible, that when you search a list of pages and data from a site, if you can not only order them in the most related first, but to also show a value.
ex. you search for data you previously entered regarding lemonade you sold. you keep track of multiple factors like "time of day, temperature, month, etc." you want to know about how much you are going to sell a week later, so you punch in values to "time of day, temperature, month, etc."
In theory, i am hoping to be able to bring up all entered data in accordance to relevance, and it shows you an estimate of what you will sell based on previous records. Any ideas?
Thanks
It would require an algorithm. i wont write all the code, but i wont mind giving some guidance :).
The html to fetch the data would be the same as the html to set the data, except it will call a seperate .php script.
The example below can be used for guidance. It uses only temperature to calculated predicted sales:
//get todays temperature from form, and query database for all temperatures
$todaysTemp = $_POST['temperature'];
$tempRange = 20; //each temperature in the table must be within this range of todaysTemp to be included in calculation
$result = $connection->query("SELECT temperature, sales FROM myTable");
//calculate average temperature by adding this temp to total, then diving by total rows included
$temp_sales_array = array();
foreach($result as $row){
if( abs($todaysTemp - $row['temperature']) < tempRange){
$temp_sales_array[$row['temperature']] = $row['sales'];
}
}
//calculate predicted sales, by getting array value thats closest to todays temperature
$closest=key($temp_sales_array[0]);
foreach($temp_sales_array as $row){
if( abs($todaysTemp - key($row)) < closest ){
closest = key($row);
$predicted_sales = $row;
}
}
//show predicted sales
echo $predicted_sales;

Categories