PHP code not executing after a fetching current date from mySQL - php

I am trying to code some manipulations that I need to perform on date format fetched from mySQL, the dates get fetched fine, having converted them TO_DAYS(), the problem is that any code after the line to fetch current date using TO_DAY(CURDATE()) does not get executed, and I cannot seem to understand why? Please Help my code is attached below:
//Final Date Calculation
$lastdate=mysql_query("SELECT TO_DAYS(date) FROM ordering WHERE id=1",$conn);
$num_rows_date = mysql_num_rows($lastdate);
while (($row_date = mysql_fetch_array($lastdate, MYSQL_ASSOC)) !== false){
$ldate[] = $row_date; // add the row in to the results (data) array
}
echo "Total number of records for the given id are: ",$num_rows_date, "<br />";
$ldatefinal=$ldate[$num_rows_date-1]['TO_DAYS(date)'];
echo "Last date in the records for the given ID is ",$ldatefinal,"<br />";
echo "Last date + Prediction days = ",$ldatefinal+$predict,"<br />";
$currentdate=mysql_query("SELECT TO_DAYS(CURDATE())",$conn);
$dcrow = mysql_fetch_assoc($currentdate);
//$dhold=$dcrow['TO_DAYS(CURDATE())'];
echo "Current Date is: ",$dcrow['TO_DAYS(CURDATE())'],"<br /" ;
//UPON EXECUTION NOTHING BELOW GETS ExEcuted ??
echo "Last date + Predicted days = ";
if(($ldatefinal+$predict)-$dcrow['TO_DAYS(CURDATE())'])<10){
echo "Time to Order<br />";
}else{
echo "You Got Gas!!";
}
mysql_close($conn);
In essence what this code is suppose to do is to get the delivery dates for a given id, than pick the last delivery date (I tried the LAST() function, but could not get it to work, I believe its for SQL SeRver), once the last delivery date has been determined (in days) it adds $predict value (the code for that is not included, but it is calculating and printing) after the addition of the two values the current date value is subtracted to see if according to a set trigger like say three days something like a push notification needs to be sent (also separate code), but in the code after correctly printing out the current date (echo line) nothing else gets executed, I have even tried putting dummy echo lines below that part to see if they would get printed, they dont!
It seems the following is the problem line in the code (I think)
echo "Current Date is: ",$dcrow['TO_DAYS(CURDATE())'],"<br /" ;
because every thing (including a simple echo test line does not get executed. Dont know why!
Please Help!
Hamood

Your if statement is not balanced with ( and ). The code is creating a parse error.
⬇︎ one more ( needed here
if((($ldatefinal+$predict)-$dcrow['TO_DAYS(CURDATE())'])<10){

Related

Updating SQL database date within PHP

Using a mysqli_multi_query to allow the user to update elements of an order (Quantity of items and chosen delivery date), the quantity query updates no problem on its own. But the delivery date part is not executing at all. The multi query does involve executing two queries on two different tables (Order & Order information), but wouldn't have thought this would be the issue.
I've tried executing the query as a standard mysqli_query (not multi) to see if it was an issue there, but the result is the same in that it is printing out the query on the page (UPDATE mytable.Order SET Chosen_Delivery_Date = '' WHERE Order_ID = '1')
From what I can see in the above (), it looks like its not reading the changed delivery date? I've tried moving the syntax around in case it was a mistake there but had no luck.
The code I've provided is the standard (not multi) query I've been working with, as would just like to get the initial query working first before i step back into making things more complicated with multi.
The code executes through 2 pages, first the page that takes the new delivery date input:
echo "<td><input type=date name='Chosen_Delivery_Date' value='".$row['Chosen_Delivery_Date']."'></td>";
echo "<td><input hidden = date name = Chosen_Delivery_Date = '".$row['Chosen_Delivery_Date']."'></td>";
Second the page that executes the query based on this input:
// This assigns the new delivery date to a variable
$Delivery = $_POST['Chosen_Delivery_Date'];
//executing the query
$update = "UPDATE Order SET Chosen_Delivery_Date='$Delivery' WHERE Order_ID = '$Order_ID'";
if(mysqli_query($conn,$update)) {
echo "Order updates sucessfully";
}
else {
echo "Error updating order: ".mysqli_error($conn);
}
All connections with the database are working no problem, but do let me know if any of you would like to see these connections or how the table is being read/echoed for the user to read before they change the the values.

age calculation & if inside if not working / php

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.)

How to perform a looping check on date/time mysql field for time values NOT equal to "00:00"?

I have a mysql table called "dobs" with a field called "dob" that is a date/time field. So examples in that field could be:
2010-09-24 01:01:00
2008-09-24 00:00:00 (this means no time was entered, only a date. I don't allow midnight to avoid confusion. If user tried to enter midnight, it would put "00:01:00" there)
I need to loop through all the fields and check to see if any of the TIME portions of that field is anything other than "00:00:00".
If just one of them has something other than "00:00:00" then I want the loop to stop because I now know what I need to know.
Here is what I have so far:
$sql = "SELECT dob FROM dobs";
$getdobs= mysqli_query($connection, $sql);
if (!$getdobs) {
die("Database query failed: " . mysqli_error($connection));
} else {
while ($row = mysqli_fetch_array($getdobs)) {
if (date("H:i", strtotime($row['dob'])!=="00:00") {
//stop loop and set $times=yes
$times="yes";
break;
} else {
//keep looping to look at next one
$times="no";
}
}
}
Now I can check $times for either yes or no to do further things I need to do. This code above works, I just worry that it's not the most efficient way to go about it. Two questions:
Did I "stop" the loop properly with "break"?
Is there a clearly more efficient way to perform this type of check?
Your code is spot on. Break is the correct reserve word to stop a loop. If your going to continue loop when the if statement isn't satisfied you can remove the else statement because it is irrelevant unless it never finds a date that is not 00:00 from the last row. Hope that helps.

how to create next/previous buttons to query MySQL rows by date?

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);
?>

Echo'ing a piece of the phpMyAdmin database in wordpress

I have a wordpress toggle function that toggles a status depending on the value in the wp_database. The user basically has the option to report sick and to report healthy. When the user reports sick i want a piece of tekst to echo out the date stored in the database. So if for example i reported myself sick on the 1st of December 2014 i want to echo out that date. The code i have so far is listed below.
$date = $wpdb->get_results( "SELECT sick FROM ziekbeter WHERE person =
$user_ID AND healthy IS NULL" );
$status="You reported sick on DATE.";
Image being the 'ziekbeter' table in my database. I know for a fact that the array it echo's only contains a single date.
Lets say that we're person 2 and we take a look at my code above.
SELECT sick FROM ziekbeter WHERE person = $user_ID AND healthy IS NULL
This would select the 'sick' row from table 'ziekbeter' (the whole table) but only the value of 'sick' where person = $user_ID (which is the user thats currently logged in to the system) and when the 'healthy' field is empty. This value (which if we're person 2 is 2014-11-13) will get put into $date. Now the only problem i face is that i need to echo this date on my website. Is there any way to do this?
The second image is of my website's front-end. You see the big red button which says 'report healthy'. If the user clicks that butten the date which they enter in the date field on the right gets put in the database (in the healthy field). (NOTE: All of this code works, im just looking for a way to output my $date on my page).
EDIT
If i var_dump the array i get the following code:
array(1) { [0]=> object(stdClass)#2315 (1) { ["sick"]=> string(10)
"2014-11-03" } }
What
print_r($array);
tells you?
Did you try
echo $array["sick"];
?
or maybe
echo $array->sick ?
$array being the name of the array containing the result of your MySQL query (the one you var_dump'ed).
Ok turns out the answer was rather simple.
$date2 = $wpdb->get_results( "SELECT sick FROM ziekbeter WHERE person = $user_ID AND healthy IS NULL" );
foreach ($date2 as $row) {
echo $row->sick;
}
I simply had to declare he had to echo the sick field again. The original SELECT did select the table at first but didnt remember that value when stored in a variable. I added a foreach row in the date variable and echo'ed the sick field. Since there is only 1 value ever in the table it has my desired result. Thanks all!

Categories