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
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 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);
?>
Any idea of what would be the best way of writing a function in PHP for an online registration system with possibility of objects' occupancy;
Just to be clear:
I want to check the availability of one object in the database by writing a function and by comparing two variables:
Starting time of reservations;
Their duration (finishing time);
So when a new reservation is entered I check the database; if it doesn't pass the limit of objects in that period (by comparing to previous reservations) it gives a message which I will then pass it to JavaScript and enable the Submission button; but if it passes the limit in my JavaScript I'll suggest a duration which is available for the entered Starting Time;
In my current PHP function I am having some problems:
First I am using so many variables and so many loops (which may cause the system slow if it gets bigger) and the code seems quite messy!
It doesn't recognize the difference between serial or concurrent reservations therefore it behaves the same to these reservations.
Here is a snippet of my function:
$reservation = new Reservation;
$reservations = $reservation -> fetch_all();
foreach ($reservations as $reservation) {
for ($j = $res_code['res_code_st']; $j < $res_code['res_code_fi']; $j++) {
for ($i = $reservation['res_code_st']; $i < $reservation['res_code_fi']; $i++) {
if ($i == $j) {
$count = $count + 1;
$arr[] = $reservation['res_code_st'];
$arr[] = $reservation['res_code_fi'];
break 2;
Which actually I'm storing time in this format;
For example for 12:30 I'm storing 1230 or for 09:20 I'm storing 0920 and then I'm checking every minute of any item with every minute of new reservation (everything happens in the same day: Days don't matter!) and in case it finds a match I count it as a new reservation in that period (the reason why it doesn't differ concurrency and serial);
I believe it should be simple but I'm kinda confused and my mind doesn't work for a better solution right now!
Thanks for your times :)
EDIT
I tried the suggested way of #kamil-maraz , I think it saves some time for reducing complexity but I still couldn't figure out how to check the concurrency.
Let me give one example:
There are four possibility of disturbance I try to show in this symbolic figure,
Suppose each line is a reservation across time, first line is for new reservation and next four are already stored in the DB;
Four disturbance are as :
One that starts before and ends at the middle of new request,
One that starts before and ends after the new request;
One that is completely inside the new reservation;
One that starts after the new request and ends after it;
0-----------------0
0--------------------------------0
0--------------0
0----------0
0-----0
$result = $db -> prepare('SELECT Count(reservation_id) FROM reservations WHERE (res_code_st < ? AND res_code_fi > ?) OR (res_code_st > ? AND res_code_fi < ?) OR (res_code_st < ? AND res_code_fi > ?) OR (res_code_st < ? AND res_code_fi > ?)');
$result -> execute(array($res_code['res_code_st'], $res_code['res_code_st'], $res_code['res_code_st'], $res_code['res_code_fi'], $res_code['res_code_st'], $res_code['res_code_fi'], $res_code['res_code_fi'], $res_code['res_code_fi']));
$row = $result -> fetch();
This is giving me the number of reservations in the interval of new request; But what about this case:
0--------------------------0
0-----0
0-----0
0------0
Although in the interval there are 4 reservations which is invalid (Suppose the #object limit == 3 ), but since at each time not more than 2 reservations are made it is still valid (the concurrency problem which I was talking about).
Any idea how should I change the SQL function to fix this ?
It seems to me, that it could be done entirely on the database. You are fetching all results and then you do some magic over data. But you can do it through a database query.
for example somethging like this:
SELECT COUNT(id) FROM reservations WHERE date < ... AND date > ... AND ... etc
then, in the php, you can test count ...
if you want to test different types of reservations, concurent, etc. you can use aggregated table (Like somebedy used here and you can store in rows types of reservations too.
I have added time stamp and date when the details should create. and the time stamp and date will add in database. When i'll retrieve it from db it wanna to show only that string name without time stamp and date ? how to make it?
Adding Method....
$imagename = $_POST['imagename'];
$imageNameExt = $_POST['imageNameExt'];
$newImgName = trim($imagename).'_'.date('Y_m_d_H_i_s').'.'.trim(strtolower($imageNameExt));
Here consider the $imagename = "abc"; and $imageNameExt = "jpg"; when it'll insert into db the name as $newImgName = "abc_2011_07_12_18_47_02.jpg"....
Now i need to retrieve from db..How should i print only the name "abc" with out the time stamp and date??
Thanks in advance.
Update : (I couldn't post this as a answer bcoz am under 100 reputation.)
found the answer for my question:
While am retrieving it'll come in the name of image_path,
$image_path = $rows[0];
$tmp = "_".date('Y');
$ImgOrgName = explode($tmp,$image_path);
$ImgOrgName_core = $ImgOrgName[0];
The Image name "abc" will come in the string "$ImgOrgName_core".
Try it...i'm easily getting the answer when i use like this.
You should store the original image name and the timestamp information as separate columns in the database. This way you will always have access to each piece of data, and you can concatenate them as you currently do before inserting any time you wish.
You can also hammer your existing code into submission by simply getting the string and counting underscores from the end until you find the 6th (there are 5 in the timestamp so the 6th from the end separates the timestamp from the name), or you can simply remove the last 20 characters from the name with substr (the timestamp is 19 chars if all numbers are padded with zeroes, plus 1 char for the separator underscore), but this kind of solution is messy and prone to breakage. I would never recommend it, so I don't give code for it (and anyway, cutting off the last 20 characters is trivial).
You cat replace date with regexp:
$imgNameNoDate = preg_replace('#_\d{4}_\d{2}_\d{2}_\d{2}_\d{2}_\d{2}#', '', $imgName);
But better way is to change your database to store original name and datetime information.
While I agree with the commenters that it would be much, much better to store the timestamp in its own column, here's how to do specifically what you want.
$underscorePos = strpos($imageNameFromDB, '_');
if ($underscorePos !== false)
{
$imageNameOnly = substr($imageNameFromDB, 0, $underscorePos);
}
found the answer for my question:
While am retrieving it'll come in the name of image_path,
$image_path = $rows[0];
$tmp = "_".date('Y');
$ImgOrgName = explode($tmp,$image_path);
$ImgOrgName_core = $ImgOrgName[0];
The Image name "abc" will come in the string "$ImgOrgName_core".
Check it...i'm easily getting the answer when i use like this.