I am looking to generate a random number say 01:20 and then add 8 hours onto that and store that as a variable. However I want to do this within only the time and not use any random integers.
The date given for the query is found using a preset date at the moment set to 01-01-2017. StaffID is gotten from a loop through another table.
This is the PHP code snippet.
strtotime($random_hour = rand(00,23));
echo $random_hour . " Hour <br> ";
strtotime($random_min = rand(01,59));
echo $random_min . " Min <br> ";
$randomhourmin = $random_hour . ":" . $random_min;
echo $randomhourmin . "<br>";
This is the final SQL insert query.
$sql = "INSERT INTO schedule (staffID, cdate, starttime, endtime, dayoff) VALUES ('$rowID','$fDate','$randomhourmin','$randomhourmin','0')";
You can use below
$int= rand(1262055681,1262055681);
Also check mt_rand(), which is to have better randomness in the results:
$int= mt_rand(1262055681,1262055681);
To turn a timestamp into a string, you can use date(), ie:
$string = date("Y-m-d H:i:s",$int);
Related
I want to calculate how much time the worker has left since break start.
By the click, PHP insert into history table a record with timestamp (break_start), after second click, PHP update record with timestamp (break_end).
Now i can calculate time difference using this code:
$break_start = $worker->query('SELECT break_start FROM history WHERE id = 16')->fetchArray();
$break_end = $worker->query('SELECT break_end FROM history WHERE id = 16')->fetchArray();
$diff = $worker->query("SELECT TIMEDIFF('".$break_end['break_end']."','".$break_start['break_start']."') AS total")->fetchArray();
$break_total = $worker->query("SELECT break_time FROM worker WHERE id = 7")->fetchArray();
echo $diff['total']." ";
echo $break_total['break_time']." ";
$str1 = strtotime($diff['total']);
$str2 = strtotime($break_total['break_time']);
Output is: 00:31:26 00:30:00.00 86 01:26
(This code above is just attempt to understand time in PHP and MySQL).
I want to subtract break time from "break" value which is stored in table "worker" (default value is 30).
I don`t know how to do this..
This question already has answers here:
mysql select int as currency or convert int to currency format?
(1 answer)
Print Currency Number Format in PHP
(8 answers)
Closed 4 years ago.
Having a lot of problems, I am using SUM on a field in my table and it works but only with one decimal place, I need it to be in currency format, I have tried the below code and others but nothing
$query = "SELECT purchase concat('$', sum(purchase), 2) from dtable";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result)){
echo "Total ". $row['SUM(purchase)'];
echo "<br />";
}
First off, please don't use the mysql* functions as they are deprecated. Move to the mysqli* functions. See the PHP Docs for more details.
How about this:
SELECT CONCAT('$', ROUND(SUM(`purchase`), 2)) AS `result`
FROM `dtable`
CONCAT just concatenates fields together so, in your case, you would end up with $###2. You need a function (like ROUND) to format the number as you want. ROUND take the number of desired decimal places as the first argument. More on ROUND (and other MySQL math functions) here: https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_round
You could also do this all in PHP using number_format.
Change
$query = "SELECT purchase concat('$', sum(purchase), 2) from dtable";
....
echo "Total ". $row['SUM(purchase)'];
to
$query = "SELECT SUM(`purchase`) AS `sumOfPurchase` FROM `dtable`";
....
echo 'Total $' . number_format($row['sumOfPurchase'], 2);
You can also use
SELECT CONCAT('$',FORMAT(sum(purchase),2)) as purchase from dtable
will give results like $1,234,567.89
I am generating random numbers using php random function, but I want the generated number should be unique and it should not be repeated again.
----------
php code
$number = rand(100,100000); //a six digit random number between 100 to 100000
echo $number;
----------
but I am using this function for multiple times in my code for users so at very rare case there should be a chance of generating same number again. how can i avoid that.
I would do this:
You said you have branches. The receipt id could look something like this:
$dateString = date('Ymd'); //Generate a datestring.
$branchNumber = 101; //Get the branch number somehow.
$receiptNumber = 1; //You will query the last receipt in your database
//and get the last $receiptNumber for that branch and add 1 to it.;
if($receiptNumber < 9999) {
$receiptNumber = $receiptNumber + 1;
}else{
$receiptNumber = 1;
}
Update the receipt database with the receipt number.
$dateString . '-' . $branchNumber . '-' . $receiptNumber;
This will read:
20180406-101-1
This will be unique(Provided you do less than 10,000 transactions a day.) and will show your employees easily readable information.
If you are storing users in DB you should create column [ID] as primary key with auto increment and that would be best solution.
In other case I'd recommend you to simply store all user id's in ascending order from N to M by reading last ID and adding 1 to it because I see no real gain from random order that only adds complexity to your code.
There are many ways, example:
$freq = [];
$number = rand(100,100000);
$times = 10;
while($times-- > 0)
{
while(in_array($number, $freq))$number = rand(100,100000);
$freq[] = $number;
echo $number . "<br>";
}
This will print 10 random unique numbers.
random_int
(PHP 7)
<?php
$number = random_int(100, 100000);
echo $number;
All you need to do is use timestamp in php as timestamp never cross each other hence it will always generate unique number.You can use time() function in php.
The time() function is used to format the timestamp into a human desired format. The timestamp is the number of seconds between the current time and 1st January, 1970 00:00:00 GMT. It is also known as the UNIX timestamp.
<?php
$t=time();
echo $t;
?>
Also you add a rand() function and insert it in front of the $t to make it more random as if few users work at same time then the timestamp might collide.
<?php
$number = rand(100,100000);
$t=time();
$random = $number.''.$t;
echo $random;
?>
The above will reduce the chance to timestamp collide hence making the probability of number uniqueness almost 100%.
And if you make your column unique in your database then the php wont insert the number hence this bottleneck will ensure you will always get a unique random number.
bill_id not null unique
If you are using it for something like user id, then you can use uniqid for that. This command gets a prefixed unique identifier based on the current time in microseconds.
Here's how to use it:
string uniqid ([ string $prefix = "" [, bool $more_entropy = FALSE]] )
Where prefix is used if you are generating ids for a lot if hosts at the same time, you can use this to differentiate between various hosts if id is generated at the same microsecond.
more_entropy increases the likeness of getting unique values.
Usage:
<?php
/* A uniqid, like: 4b3403665fea6 */
printf("uniqid(): %s\r\n", uniqid());
/* We can also prefix the uniqid, this the same as
* doing:
*
* $uniqid = $prefix . uniqid();
* $uniqid = uniqid($prefix);
*/
printf("uniqid('php_'): %s\r\n", uniqid('php_'));
/* We can also activate the more_entropy parameter, which is
* required on some systems, like Cygwin. This makes uniqid()
* produce a value like: 4b340550242239.64159797
*/
printf("uniqid('', true): %s\r\n", uniqid('', true));
?>
this code must work
some description about code:
generate unique id
extract numbers form unique id with regex
gathering numbers from regex with a loop
<?php
$unique = uniqid("",true);
preg_match_all("!\d+!", $unique ,$matches);
print_r($matches);
$numbers = "";
foreach($matches[0] as $key => $num){
$numbers .= $num;
}
echo $numbers;
I am trying to add a timestamp to my database when I update a form, and for reason that I do not know, I am getting an error... and when just trying to insert the year, month, day I get "1988" inserted into my database. I use a similar timestamp elsewhere on the same site and it works fine. What am I doing wrong?
Note: yes I know I should be using mysqli and I'm vulnerable to sql injection. I plan on converting the entire site later in the year.
$homeScore = ((strlen($game['homeScore']) > 0) ? $game['homeScore'] : 'NULL');
$homeOdds = (str_replace("\xBD", ".5", $homeScore));
$visitorScore = ((strlen($game['visitorScore']) > 0) ? $game['visitorScore'] : 'NULL');
$visitorOdds = (str_replace("\xBD", ".5", $visitorScore));
$odds_timestamp = date("Y-m-d g:i:s A");
$sql = "update " . $db_prefix . "schedule ";
$sql .= " set odds_timestamp = " . $odds_timestamp . ", homeOdds = " . $homeOdds . ", visitorOdds = " . $visitorOdds . "";
$sql .= " where gameID = " . $game['gameID'];
mysql_query($sql) or die('Error updating odds: ' . mysql_error());
You have missing (single) quotes " . $odds_timestamp . "
that will need to be '" . $odds_timestamp . "' since it will contain characters that MySQL will complain about... being hyphens.
That is a string.
Now, if any of your other variables are also strings, they too need to be quoted as shown.
I.e.: '" . $string . "' as opposed to " . $integer . "
More on string literals:
https://dev.mysql.com/doc/refman/5.0/en/string-literals.html
Pay attention to Riggs' comments, one of which being:
"You would be best advised to make the datatype a DATETIME or TIMESTAMP as if you keep the VARCHAR it will make the data much more difficult to process later. Just change the date() to produce a legal MYSQL data format"
Using a VARCHAR won't fix it, as it still considered as a string literal for the column.
New comments by Riggs:
"You would be best advised to make the datatype a DATETIME or TIMESTAMP as if you keep the VARCHAR it will make the data much more difficult to process later. Just change the date() to produce a legal MYSQL data format. You can always add the AM/PM when you present the date time to any user. VARCHAR date/time will really mess with your selection criteria later as well. Remember - Database for DATA, Browser for PRESENTATION"
You can use MySQL's NOW() function, which returns current datetime.
Without error message, Its difficult to say something.
or if you can print your query it will be helpful.
but try with.
odds_timestamp = '" . $odds_timestamp . "'
to make it explicit string.
Try adding a timestamp column in the database table with an on update set current timestamp clause.
Heres a simple example from MySQL Documentation:
CREATE TABLE t1 (
ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
Should take care of it and cut out the middle man. Win-win.
I am usng sqlite to log data every 5 minutes to a column that is time stamped with and integer in Unix time. The user interface uses php code to extract data in various user selectable time frames which is then plotted using javascript. Charts typically have 12 data/time points and I need to extract data for plotting over different periods of say 1Hr/12Hr/24Hr/12days/month/year. So only need to extract 12 data rows per search. So for a 24Hr plot I need to only extract data at houly intervals (when minutes = 0) similarly for 12day plots at daily intervals (when mins=0 && hours=0) etc.
My php code for 1Hr works fine since the data is logged every 5min giving me 12 rows of data between search start time and end time. What is an efficient way of extracting data for the longer periods when number of rows between start time and end time is greater than 12? I need to further filter the search to efficiently extract only the data I need?
any suggestions - most appreciated - frank
$db = new MyDB(); // open database
$t=time(); // get current time
$q1 = "SELECT TimeStamp,myData FROM mdata WHERE ";
$q2 = " AND TimeStamp <=".$t; // end time
$q3 = " AND TimeStamp >=".($t-3600); // start time 1 hour earlier
$qer = $q1.$q2.$q3; // my search query form above parts
$result = $db->query($qer);
$json = array();
while ($data = $result->fetchArray(SQLITE_NUM)) {
$json[] = $data;
}
echo json_encode($json); // data is returned as json array
$db->close(); // close database connection
I think you should use WHERE date BETWEEN in your search query?
This kind of search could take up a lot of time once data builds up?
Since you already know the exact times you're interested in, you should probably just build an array of times and use SQL's IN operator:
$db = new MyDB(); // open database
$timeStep = 300; // Time step to use, 5 minutes here - this would be 3600 for hourly data
$t = time(); // get current time
$t -= $t % $timeStep; // round to the proper interval
$query = "SELECT TimeStamp,myData FROM mdata ";
$query .= "WHERE TimeStamp IN "
$query .= "(" . implode(",", range($t, $t + $timeStep * 12, $timeStep)) . ")";
$result = $db->query($query);
$json = array();
while ($data = $result->fetchArray(SQLITE_NUM)) {
$json[] = $data;
}
You'll need to do some different math for monthly data - try constructing 12 times with PHP's mktime() function.
Here are the references for the PHP implode() and range() functions I used.