I assume, I need Ajax and jQuery to show new data based on date after clicking a button.
What I want to do is something like this:
<< January 15................today: January 16..............January 17 >>
Data4
Data5
Data6
When I click "January 17" data 4-6 should change to data 7-9 because data 7-9 is added to the MySQL database on January 17.
Of course I have a code to query the database and show today's data, but I am going crazy about not being able to reload the page with new data.
I tried to search the whole internet, but nothing I can find fits my needs.
Your question has a lot of sides to it. This answer's solely purpose to demonstrate how front end, back end and persistence layer communication works.
DO NOT USE THIS IN PRODUCTION! THIS CODE IS SHITTY AND FOR DEMO PURPOSES ONLY!
Modern web applications are not implemented like this. Front end frameworks/libraries are commonly used to keep complexity manageable.
First of all your back end should provide an API to the front end.
Lets assume your back end accepts the following HTTP GET request:
www.example.com/users/list_by_date/20150131
The last parameter is a date in YYYYMMDD format. Upon receiving this request, your back end sends a pre-rendered HTML snippet containing a list of users from that date. (Nowadays front end side rendering is quite popular and you should look into that topic as well. In this case your back end sends a list of users in JSON format which is then rendered on the front end side using templates. Adding code for this would make example even more complex).
In order to get this list of users, you initiate an AJAX request from the front end when a user clicks on a next-day button (which in your example contains "January 17"). Furthermore, you need to replace a list of currently shown users from January 16th with the new ones. Lets assume that list has a class attribute .users in HTML code. Here is a front end code using jQuery:
$(function() {
$(document).on('click', '.next-day', function() {
$.getJSON("/users/list_by_date/20150131", renderResults);
});
function renderResults = function(data) {
$('.users').html(data); // replaces old contents with the new ones received from server
};
});
You should also update prev/next link titles to the next dates, January 16th and January 18th respectively.
On the back end side, you execute a SQL statement to fetch a list of users. It could look something like this:
SELECT * from Users where DATE(datetimecolum) = '2015-01-17'
The exact way to put an attribute into a SQL query varies among programming languages/frameworks.
This should help you start working on your own solution. You probably should at least consider a front end framework/library to help you manage the complexity. You might want to spend a few days or even weeks getting familiar with front end technologies before attempting to implement a good solution on your own. It might be more cost efficient to hire a front end developer.
I did it on my own and the code actually were 5 lines.
I needed 2 days. Somebody who knows it, could have written it up in 2 minutes. So thanks for all the fish!
Here is the code, if somebody ever needs something like this:
The code for determining the very last date available (which I had already):
$query = mysqli_query($bd, "SELECT MAX(datum) as max_datum, MIN(datum) as min_datum FROM apps WHERE price = 0 ") or die(mysqli_error());
$maxdate = mysqli_fetch_assoc($query);
$maxdate = $maxdate['max_datum'];
$mindate = $mindate['min_datum'];
The actual code I was looking for to display two links for next and previous days (without design):
$date = isset($_GET['date']) ? $_GET['date'] : $maxdate;
$prev_date = date('Y-m-d', strtotime($date .' -1 day'));
$next_date = date('Y-m-d', strtotime($date .' +1 day'));
if ($date < $maxdate) {
echo "<a href=?date=$next_date>forward a day</a>";
}
if ($date > $mindate) {
echo "<a href=?date=$prev_date>back a day</a>";
}
The code executing the data which I had already:
$result = mysqli_query($bd, "SELECT * FROM apps WHERE datum = '".$date."' AND price = 0 ") or die(mysqli_error());
$count = mysqli_num_rows($result);
echo "<div id='icon-wrapper'>";
$cc = 0;
while ($row = mysqli_fetch_array($result)){
...
$cc++;
if ($cc < $count) {
echo "\n";
}
}
echo "</div>";
mysqli_close($bd);
?>
Related
I have a code that looks like this:
$dagtidhelg = gmdate('H:i', $diffMorning) . "\n";
$kvallstidhelg = gmdate('H:i', $diffNight);
This code runs several times per page since its runt every time a row is loaded from mysql.
It can return a time value ie 08:15 and 09:30. This is the lenght of two work sessions.
That works great but now Im stuck, I want to display the total of every work session at the bottom. I have tried this:
$dagtidhelgtotal = $dagtidhelgtotal + $dagtidhelg;
$kvalltidhelgtotal = $kvalltidhelgtotal + $kvallstidhelg;
But that only adds the hours togheter, it wont even display the :
So Im guessing that Im doing this totaly wrong.
How can I add these times togheter? Maybe convert them to minutes, then add them all togheter?
Add duration together is simple .But you must keep in mind that duration and date are two things completely different. You can write 100:08 for duration but not for date. If your purpose is to keep a duration counter on(one or) every page(s) you need to build a system based on $_SESSION variable.
To add two duree you can proceed like this:
function addDuration($duration1,$duration2){
$result=array_map(function($x,$y){return sprintf("%'.02d", $x+$y);},explode(':',$duration1),explode(':',$duration2));
if($result[1]>60){
$result[0]=sprintf("%'.02d",$result[0]+(int)$result[1]/60);
$result[1]=sprintf("%'.02d",$result[1]%60);
}elseif($result[1]==60){
$result[1]="00";
$result[0]=sprintf("%'.02d",$result[0]+1);
}
return join(':',$result);
}
and the usage in your case could be:
$dagtidhelgtotal = addDuration($dagtidhelgtotal,$dagtidhelg);
if we suppose that
$dagtidhelgtotal ==='100:09' && $dagtidhelg === '08:08'
then after the addition
$dagtidhelgtotal will be equal to '108:17';
I am trying to convert three separate database columns into a date (day,month,year) and calculate the age so only users over the age of 15 or 18 can purchase certain products. The code below doesnt work as it echoes '0 days, 0 months, 0 years' and still adds the product to the basket. Which means the age calculation doesnt work, and my first if statement doesnt work either.
<?php
$username = $_SESSION['solentuser'];
echo "$username's account!<br>";
$conn = new PDO("mysql:host=localhost;dbname=u;","u","p");
$productID= htmlentities($_GET['ID']);
//startdate
$result=$conn->prepare("SELECT * FROM users WHERE username=:username");
$result->bindParam(":username",$username);
$result->execute();
$row=$result->fetch();
$birthdate = $row['yearofbirth'] . $row['monthofbirth'] . $row['dayofbirth'];
$presentdate = date('Ymd');
$birthday = new DateTime($birthdate);
$currentdate = new DateTime($presentdate);
$age = $birthday->diff($currentdate);
echo $age->format('<br>%d Days %m Months %y Years<br>');
//enddate
$results=$conn->prepare("SELECT * FROM products where ID=:productID");
$results->bindParam(":productID",$productID);
$results->execute();
$row=$results->fetch();
if($row['agelimit'] <= $age){
if($row['stocklevel'] >= 1){
$result=$conn->prepare("INSERT INTO basket(productID,username,qty) values(:productID,:username,1)");
$result->bindParam(":productID",$productID);
$result->bindParam(":username",$username);
$result->execute();
$result=$conn->prepare("UPDATE products SET stocklevel=stocklevel-1 WHERE ID=:productID");
$result->bindParam(":productID",$productID);
$result->execute();
echo "You have successfully added this product to your basket!";
}
else{
echo "This product is out of stock!";
}
}
else{
echo "You are not old enough to purchase this product!";
}
//print_r($conn->errorInfo());
?>
any suggestions as to where the error is? i have read that it is possible to write an if statement inside an if statement, so why does this one not work?
thank you!
I'd echo out $birthdate and verify there's a valid date there. (We aren't getting back single digits, a date of 2009-05-04 getting represented as '2009', '5' and '4' such that when we concatenate them, we get 200954, or maybe extra spaces. (We're not seeing the datatypes of the three separate columns.)
We might try adding some delimiters in there, so we'd get 2009-5-4, likely we could get that converted into a DateTime, using the correct format string.
If I had separate values for month, day and year, I would use PHP mktime, and then create a DateTime object from that.
(MySQL does provide a DATE datatype that allows for a very large range of valid dates, and doesn't allow invalid dates to be stored. Storing three separate columns to represent a single date just smells like the wrong way to do it. (If I actually needed the separate month and day columns (to allow indexing for some queries), I would add those in addition to the birthdate DATE column, not in place of it, with triggers to keep the values in sync with the birthdate column.)
Also, $age is a DateInterval object. You seem to be aware that we can use the format method to extract integer number of years.
$age_yrs = $age->format('%y');
We're guessing that the database column age_limit is integer years.
if( $row['agelimit'] <= $age_yrs ) {
Right before that if statement, we can confirm that what we think to be true is actually true...
echo " age_yrs=" . $age_yrs;
echo " row_age_limit=" . $row['age_limit'];
Looking closely at the debugging output helps us identify if the problem is before the if statement or after, so we aren't chasing down a problem in a section of code where there isn't a problem, the problem is somewhere else, on a preceding line.
I encourage you to develop the skills needed to debug programs that you write. It seems like you are making some (wrong) assumptions about what the variables are containing.
Adding echo and var_dump during development is a first step in verifying that what you think to be true is actually true.
I'd go as far as recommending that you look at every line of code you write as possibly going wrong, especially in edge cases.
https://ericlippert.com/2014/03/05/how-to-debug-small-programs/
(StackOverflow is a question/answer community, not a debugging service.)
I am providing 24 hours trial membership in my android application. I do not know more about PHP. I want check user registration time and want disable trial membership if 24 hours got passed. I have made little PHP file for that.
$sql = "SELECT id, email, registration_time FROM user WHERE trial = 1";
$result = $conn->query($sql);
if($result) {
while($row = $result->fetch_row()) {
$id = $row[0];
$email = $row[1];
$registrationTime = strtotime($row[2]);
$currentTime = strtotime("-1 day");
if($currentTime > $registrationTime) {
$update = "UPDATE user SET trial = 0 WHERE email = '$email'";
$conn->query($update);
$update = "UPDATE number_list SET disable = 1 WHERE user_id = $id";
$conn->query($update);
}
}
}
Its not providing any result even I have one user which time passed more than 48 hours.
How can I solve this issue?
try this and check
$currentTime=date('m-d-Y',strtotime($registrationTime . "-1 days"))
You should use a prepared statement to update the database for all the users with the same email (your first update query). Also see the documentation.
If someone registers with an e-mail address like test'; DROP ALL TABLES; --#gmail.com1 this code will dutifully remove your database. Never put user data into code directly like that.
Now let's look at the example code;
$sql = "SELECT id, email, registration_time FROM user WHERE trial = 1";
$result = $conn->query($sql);
if($result) {
while($row = $result->fetch_row()) {
You're saying there is no result at all. I assume that you've tested the output with a debug statement. E.g. putting echo 'users exist'; in between here. The first thing to do would be to check your user table if there are any rows. Does this SQL query produce results?
Assuming that it does, there doesn't appear to be anything wrong with the SQL statement. Assuming you have a table called user with four columns id, email, registration_time, and trial it should produce results.
Next, what you want to do is read the query function documentation. As you can see there, when a query fails, for whatever reason, it returns FALSE. Try writing an 'else' code block and logging the error that occurs. You can fetch it using the error function mysqli::error. Try appending this code;
} else {
echo "MySQL Error: " . $conn->error;
}
Where you can replace the echo with your error handling of choice.
It's probably a good idea to write a wrapper for mysqli if you're going to execute more than a few queries in your application. That way, you can write error handlers in your wrapper class for what your application should do if a query or database connection fails.
What could also be the case is that, while your initial query succeeds and fetches some rows, the time check fails. You may want to do some stricter date/time parsing than using strtotime and hoping for the best. Assuming you're using a TIMESTAMP column to store the data, you can use this:
function readDatabaseTimestampValue($value) {
$dateTime = date_create_from_format("Y-m-d H:i:s", $value);
$timestamp = $dateTime->getTimestamp();
return $timestamp;
}
Check the exact time data returned from your database. Dates and times are complicated, and if things are reinterpreted, say the day number in SQL may become the year in the PHP app, which can cause strange bugs. E.g. you can do this by doing say:
echo "24 hours ago: " . strtotime("-1 day") . ", user data: " . $row[2];
Next, you probably have some bugs in the logic. '24 hours ago' is better done by doing this, as using '-1 day' will cause weird issues when people mess with the calendar:
$timestamp = time() - 86400;
There's 86,400 seconds in a day (well, excluding DST and leap seconds, but you want 24 hours of subscription time, not 23 hours around the 21st of March).
Finally, there's problems if the same E-mail address is present more than once in the table. You will set 'trial' to 0 for one user, but may set the 'disable' flag for another if two users register within the same 24-hour period with the same e-mail. If the latter is guaranteed to be unique then this is no issue. Otherwise, you may want to update by id in both tables.
Next, we can look at some optimization. Right now, you fetch everything from the database. But you can do much better/faster by having an index on registrationTime, and using the database's sorting features. E.g. let's say we know the exact date/time of 24 hours ago as $yesterday in PHP we can write a query like:
SELECT id, email, registration_time FROM user WHERE trial = 1 AND registration_time > ?
Bind the $yesterday variable to the parameter. Now you no longer need the if() statement; the database does it for you. Also, as your database grows, you're not checking the old records one-by-one every time the code runs.
1Note, that may not be a legal e-mail address, but there's probably ways to do evil things even with a legal mail address.
I'm working with WHMCS 5.3.x which has Smarty 2.x IIRC.
So for instance {$service.regdate} renders:
2015-06-01
What I need to do is add one month to that date:
2015-07-01
...which I can then format with:
|date_format:"%m/%d/%Y"
...to display it how I want it.
I've tried quite a few things based on Google results like:
{"+1 month $service.regdate"|date_format:"%m/%d/%Y"}
{strtotime("+1 month",$service.regdate)|date_format:"%m/%d/%Y"}
...and a few other various iterations but the output generally renders only my initial date or nothing at all.
I'd also need to generate the number of days left from $smarty.now to $service.regdate + 1 month so I can show my customers how many days are left.
This I haven't found nearly as much information on.
I know you can do most if not all of this in PHP and then assign it to Smarty variables, but, I haven't found an example that works and, if you've ever worked with WHMCS support before, they don't really give you much to go on other than to "ask the forums", "talk to modulesgarden" or "open a feature request"
Thank you =)
Sylvain is 100% correct and using MySQL is the proper resolution:
{php}
$userid = $this->_tpl_vars['clientsdetails']['id'];
$result = mysql_query("
SELECT *,
DATE_ADD(tblhosting.regdate,INTERVAL 1 MONTH) as trialexpires,
DATEDIFF(DATE_ADD(tblhosting.regdate,INTERVAL 1 MONTH),CURDATE()) as trialdaysleft
FROM tblhosting,tblproducts
WHERE userid = $userid
AND tblhosting.packageid= tblproducts.id
AND tblhosting.domainstatus='Active'"
);
$services = array();
while ($data = mysql_fetch_array($result)) {
array_push($services, $data);
}
$this->_tpl_vars['services'] = $services;
{/php}
Thank you =)
How would I go about programming a daily message on my site that changes daily? I'm thinking of preloading all the messages in a MySQL database.
Any help would be appreciated!
Thanks,
I've tried
$msg_sql = "SELECT * FROM ".TABLE_PREFIX."quotes ORDER BY rand(curdate()) LIMIT 3";
$msg_res = mysqli_fetch_assoc(mysqli_query($link, $msg_sql));
But this only grabs the first MySQL result?
If you want a real message changing daily, you actually don't need to rely on a database or anything fancy. A simple idea might be to create a directory (say /var/www/motds) and populate it with files named YYYY-MM-DD.txt (where YYYY is a 4 digit year number, MM is a two digit month number and DD is a 2 digit day number).
Then, the only thing you need to do in order to display your motd is:
$filename = '/var/www/motds/'.date("Y-m-d").'.txt';
if (file_exists($filename)) {
echo file_get_contents($filename);
}
If you want your daily messages to be taken from a pool of entries (that you can pre-load), you might do something as follows:
$files = scandir('/var/www/motds'); // put files into an array
$messagecount = count($files) - 2; // .. and . shall not be considered
$day = date("z"); // what day do we have today?
echo file_get_contents('/var/www/motds/' . $files[($day % $messagecount) + 2]);
There are plenty of ways to get this done. You list PHP in your tags, so maybe check here:
PHP Script: Quote of the Day
or maybe here