Date and Format issues in PHP - php

I am new here and this is my first question. Well, here it goes:
What I need to do is to create a PHP that compares an array of birthdays (dates) from a database (mysqli query) to the actual date (particularly month and day, ignoring the year for obvious reasons) so it can confirm "This person's birthday is today" through an echo or something.
I am having trouble formatting the date from the sql array. Here's what I got so far:
<?php
$link = mysqli_connect("localhost", "root", "", "employees");
$actualdate = date('md');
if (mysqli_connect_errno()) {
printf("Conection failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT BirthDate FROM Birthdays";
if ($result = mysqli_query($link, $query)) {
while ($row = mysqli_fetch_row($result)) {
if (in_array($actualdate, $row)) {
echo "Birthday!";
} else {
echo "No birthday";
}
}
mysqli_free_result($result);
}
mysqli_close($enlace);
?>
Thanks beforehand, and sorry for the botherations.

Assume BirthDate is stored as a DATE. I would probably only select the Birthdays that are today:
SELECT BirthDate
FROM Birthdays
WHERE DAY(BirthDate) = DAY(NOW()) AND MONTH(BirthDate) = MONTH(NOW());

If you still want to echo "No birthday" you need to check the date format in the database. Normally the date format in the MySQL is YYYY-MM-DD. So you need to change the date creation code to
$actualdate = date('Y-m-d');
That will do.. Otherwise you can choose #jim's answer, to get only today's birthdays.

Related

Update Automatic Mysql Values php

Hello I want to update MySQL table automatic at set time like i want to update table at 5:30 i have some values to update in my database at set time automatic. in PHP
$date = date('H:i:s');
if($date == "11:26:00") // 17:30:00 is equal to 5:30 but in 24 system
{
$sql1 = "SELECT * FROM No where id='1'";
$result1 = mysqli_query($mysqli,$sql1) or die(mysqli_error());
while($row= mysqli_fetch_assoc($result1))
{
$Foo= $row['foo'];
}
$sql2 = "UPDATE No SET id='2',foo='$foo' where id='2'";
$result2 = mysqli_query($mysqli,$sql2) or die(mysqli_error());
}
Just lie what Ashish said you can use CRON , and if you want you maybe can use this , i did not use before , try it . This code will works once ,so you have to find away to make loop cause the time will change every sec .
Note : Check the second code .
<?php
// Database connect
$date = date('H:i:s'); // Set the time to hours and minutes and seconds format
// you can echo $date to check how it looks but it will be something like this : 07:21:48
if($date == "17:30:00") // 17:30:00 is equal to 5:30 but in 24 system
{
// You can type your code here .
}
?>
Second Code :
<?php
// Remember to connect to your database
$date1 = date_create("00:00");
$date2 = date_create("23:59");
while($date1<=$date2)
{
date_add($date1,date_interval_create_from_date_string("1 sec"));
$a = date_format($date1,"H-i-s");
if($a =='17:30:00')
{
$sql1 = "SELECT * FROM No where id='1'";
$result1 = mysqli_query($mysqli,$sql1) or die(mysqli_error());
$row= mysqli_fetch_assoc($result1)
{
$Foo= $row['foo'];
$sql2 = "UPDATE No SET id='2',foo='$foo' where id='2'";
$result2 = mysqli_query($mysqli,$sql2) or die(mysqli_error());
}
die;
}
else
{
// you can type anything here , you can end the process by typing die; or anything you want
}
}
?>
You can check this and see how you can loop throw date in php :
I have 2 dates in PHP, how can I run a foreach loop to go through all of those days?
This can help you understand the time and date system and how to change the format for the date in php : How to get the current date and time in PHP?

Trying to SELECT a record in an sqlite database using php

I am trying to select one record from the table tblTermDate. I am only getting an output of 1 for both. There is data entered into the fields and the format is VARCHAR for both dates. Any help would be appreciated Thanks!
<?php
// create or open database called TimeTable.sqlite
$db = #sqlite_open("TimeTable.sqlite");
//Get Start Date from Table
$StartDate = #sqlite_exec($db, "SELECT fldStartDate FROM tblTermDate WHERE fldTerm_Name ='Christmas 1st Half' ");
//Print Start Date
echo $StartDate;
echo "<br> </br>";
//Get Start Date from Table
$EndDate = #sqlite_exec($db, "SELECT fldEndDate FROM tblTermDate WHERE fldTerm_Name ='Christmas 1st Half' ");
//Print End Date
echo $EndDate;
//Database Close
#sqlite_close($db);
?>
sqlite_exec executes a SQL statement and does not return any rows. Its return value is true if the statement was executed successfully and false otherwise. Hence your "output" of 1.
What you are looking for is the sqlite_query method: http://www.php.net/manual/en/function.sqlite-query.php

php compare current date with dates stored in database

I am trying coding a php script where i want to extract a date field from a database table,store this date compare it with todays. To see if the data. from database has passed or not compared to todays date.
the code i have written for this functionality looks like its not working
I think i am getting the date() format wrong.
I am not to sure about the logic if statments.
php
$sql="SELECT enddate FROM campaigns WHERE id=".$data['camp'];
$result = mysqli_query($db, $sql);
while($info = mysqli_fetch_assoc($result)){
if(date("Y-m-d") > $result){
exit;
echo "Success";
}
elseif(date("Y-m-d") < $result){
return true;
echo "Failure";
}
}
Use strtotime()
while($info = mysqli_fetch_assoc($result)){
if(strtotime(date("Y-m-d")) > strtotime($result)){
exit;
echo "Success";
}
elseif(strtotime(date("Y-m-d")) < strtotime($result)){
return true;
echo "Failure";
}
}
You have to do:
if(date("Y-m-d") > $info['enddate']) {
Youl could just let MySQL worry about it.
SELECT DATEDIFF(NOW(),enddate) FROM campaigns WHERE id=".$data['camp']
That will return the number of days between the two dates. See the manual for DATEDIFF.
You can use below query :
$sql="SELECT (CASE WHEN DATE(NOW()) > enddate THEN 'success' ELSE 'failed' END) AS mystatus FROM campaigns WHERE id=".$data['camp'];
Then you just need to call mystatus column from the query.
I spend lot of time to compare only dates and i found a solution like this
Always set format like date('Y-m-d')
$dateTo='2016-08-07';
if(date("Y-m-d", strtotime($dateTo)) > date('Y-m-d')){
echo 'yes';
}else{
echo 'no';
}

How do I adjust the Date Format when it is in an array?

I can't figure out how to isolate only the Date variable in an array that is pulling all of the keys from MYSQL. I want to make it format %M %d. How can I pull it out of $dataFields array modify it then put it back in? The Key is "Date".
include('include/connect.php');
$table='currentJobs';
$sql="SELECT * FROM `".$table."`";
$result=mysql_query($sql,$dbLink);
$data=array();
$d=0;
while($row=mysql_fetch_assoc($result)){
$dataFields=array();
while(list($key,$value)=each($row)){
$dataFields[]='<td class="'.$key.'" >'.$row[$key].'</td>';
if ($d==0){
$dataKeys[]='<th class="'.$key.'" >'.$key.'</th>';
}
}
if ($d==0){
$data[$d]='<tr>'.join('',$dataKeys).'<th class="actions">Actions</th></tr>';
$d++;
}
$data[$d]='<tr>'.join('',$dataFields).'<td>
Update</td></tr>';
$d++;
}
mysql_free_result($result);
if ($d>0){
echo '<table class="sortable">'.join('',$data).'</table>';
}
else {
echo 'Sorry, data was not found';
}
mysql_close($dbLink);
It is currently Displaying:
Date Name Phone Bike_Year Bike_Model Current_Status Service_Type ▴ Mechanic Revenue Notes Actions
0000-00-00 Test User 206-555-5555 2001 FLHRI Checked In Spec Service Interval Johhny 840.30 Update
$sql="SELECT
date_format(date, '%M %d') AS date,
Name,Phone,Bike_Year,Bike_Model,Current_Status Service_Type,Mechanic,Revenue,Notes
FROM `".$table."`";
This method is less efficient then just modifying the format within the SQL as suggested by JOE LEE. But either way works, whichever you prefer should work.
if($key == 'Date'){
$dataFields[]='<td class="'.$key.'" >'.date('M d',strtotime($row[$key])).'</td>';
} else {
$dataFields[]='<td class="'.$key.'" >'.$row[$key].'</td>';
}
or compact:
$dataFields[] = $key == 'Date' ? date('M d',strtotime($row[$key])) : $row[$key];
Look here for the date format options:
http://us1.php.net/manual/en/function.date.php

Comparing date from variable to MySQL date

I'm comparing date specified in PHP with dates in MySQL table and then echoing all rows with dates after the date in PHP. It works OK when I specify the date in the SELECT command, but when I make it a variable it doesn't work.
My PHP is:
$sql = "SELECT event FROM LifeEvents WHERE event_date > '1995-02-27'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["event"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
This works ok. But when I replace the SELECT with:
SELECT event FROM LifeEvents WHERE event_date > $date
It no longer works.
For the variable I've tried working with both:
$date = new DateTime('1995-02-27')
and
$date = '1995-02-27'
Neither of them works. The data type in MySQL is DATE.
For the string variable
$date = '1995-02-27'
$sql = "SELECT event FROM LifeEvents WHERE event_date > '$date'";
// this should work exactly as
$sql = "SELECT event FROM LifeEvents WHERE event_date > '1995-02-27'";
For the DateTime object, this should work
$date = new DateTime('1995-02-27')
$sql = "SELECT event FROM LifeEvents WHERE event_date > '" . $date->format(Y-m-d). "'";
I suggest you always set the timezone when you are dealing with dates and times because underestimate timezones can result in really bad bugs specially if your applications is dealing with many timezones and you have timestamp data type in your database.
make it a habit to do this
define('DEFAULT_TIMEZONE','UTC');//set this in your global config.php file
$date = new DateTime('2000-01-01', new DateTimeZone(DEFAULT_TIMEZONE));
Lets create a variable that holds a date and then convert it to date format that MySQL can understand.
$dt = date('Y-m-d', strtotime('1995-02-27')); // maybe filled dynamically
$sql = "SELECT event FROM LifeEvents WHERE event_date > '$dt'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["event"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
Then change what you want in order to serve your needs.
Hope I pushed you further.
That's because '1995-02-27' and DateTime('1995-02-27') are both not valid in that case :
'1995-02-27' would work if you'd have put extra quotes around $date in your SQL query : "SELECT event FROM LifeEvents WHERE event_date > '$date'"
DateTime('1995-02-27') doesn't have a __toString() magic method so PHP is unable to represent it as a string. You have to use the format method : $date = $date->format('Y-m-d') (and it will still miss the quotes)
One or another solution, you need to protect yourself against SQL injections using prepared statements! And you will actually no longer need any quote.
Try using the Carbon library for PHP.
Store a date with PHP:
$current_time = Carbon::now()->toDateTimeString();
Then just compare it the same way.

Categories