How to pass month and year in url - php

I am displaying a list of months and years from the database like this into a drop-down menu:
$stmt = $link->prepare("SELECT `b_date` FROM `summary` GROUP BY YEAR(`b_date`), MONTH(`b_date`)");
$stmt->execute();
$result = $stmt->get_result();
$numRows = $result->num_rows;
if($numRows > 0) {
while($row = $result->fetch_assoc()) {
$month = date('F Y', strtotime($row['b_date']));
echo "<option value='{$month}'>{$month}</option>";
}
}
When the user clicks on a choice, it redirects to another page like:
mypage.com/results.php?date=
The problem is that I don't know what to set the value as. In the current code the url produced looks like:
php?date=April%202017
That obviously isn't ideal. And the point is that on the results page I need to show results for the month that was selected. So, I need that query string to query the database.

You can put to select value something like 05-2017:
while($row = $result->fetch_assoc()) {
$month = date('m-Y', strtotime($row['b_date']));
echo "<option value='{$month}'>{$month}</option>";
}
And then get it with DateTime object:
$date = DateTime::createFromFormat('m-Y', $_GET['date']);
And then you can format this object to any format you want:
$formated_date = $date->format('Y-m-d');
You can chose another format, but I think you understand my idea.
UPD. To execute all record on this month try to use this code:
$date = DateTime::createFromFormat('m-Y', $_GET['date']);
$stmt = $link->prepare("SELECT * FROM `summary` WHERE YEAR(`b_date`) = :year AND MONTH(`b_date`) = :month");
$stmt->bindParam(':month', $date->format('m'));
$stmt->bindParam(':year', $date->format('Y'));
$stmt->execute();
$result = $stmt->get_result();
I think its working but maybe need to fix.

Change like this (use urlencode()):-
$month = date('m-Y', strtotime($row['b_date']));
echo "<option value='".urlencode($month)."'>{$month}</option>";
Now on next page check $_GET['date'] and see it's coming proper or not?
if it come proper in format like m-Y then split it with - and now you get month and year separately. Use them in your query or wherever you want.
Query need to be like something:-
$_GET['date'] = '04-2017';
$date_array = explode('-',$_GET['date']);
$month = $date_array[0];
$year = $date_array[1];
"SELECT * FROM summary WHERE MONTH(<you date column name>) = $month";

U can format data in select (postgres, mysql...)
SELECT TO_CHAR('MM-YYYY', b_date) AS formated_date FROM summary GROUP BY TO_CHAR('MM-YYYY', b_date

Related

Get Data From a Query With Several Cases

I have a search field with 3 fields (2 field for date range and 1 field for person). I would like if I select the person, then the data based on this person to appear on the screen. Same as I am using the while loop below.
When I select the date range, only the data for this date range to appear on the screen. I am able to do that using the following query.
$startDate = $_POST['startDate'];
$endDate = $_POST['endDate'];
$employer = $_POST['employer'];
$sql = "
SELECT *
FROM jobs
WHERE employer_id = '$employer'
OR (endDate BETWEEN '$startDate' AND '$endDate')
";
$res = mysqli_query($db, $sql) or die(mysqli_error($db));
I would also want if I select both the date range and the person field, then I would like the data for both of them to appear on the screen with the while loop shown below.
I want this to be achieved using the query above, but I do not have a solution.
Then, I extract all data in a while cycle:
while($row = mysqli_fetch_assoc($res))
{
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$title = $row['job_title'];
$date = $row['endDate'];
}

Get SQL table data for current month using prepared statement PHP

Here is a code which I am using to get current month data from table wp_formdata
HTML :
<div class="result" id="result" name="result">
<?php echo $head1; ?> <?php echo $out; ?> <?php echo $head2; ?>
</div>
PHP:
if ($_POST['result_options'] == 'Current_Month') {
$now = new \DateTime('now');
$CurrMonth = $now->format('m');
$CurrYear = $now->format('Y');
$sql ="Select date,select_bank,entry_type,income_cat,expense_cat,amount,expense_cat_sub from wp_formdata WHERE MONTH(?) = MONTH(CURRENT_DATE()) AND YEAR(?) = YEAR(CURRENT_DATE()) order by date ";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt,$sql)) {
$message = '<h1 style="color:red;padding-top:5%;">SQL Error !!</h1>';
} else {
mysqli_stmt_bind_param($stmt,"ss", $CurrMonth, $CurrYear);
mysqli_stmt_execute($stmt);
$result= mysqli_stmt_get_result($stmt);
$out = "";
while($row = mysqli_fetch_assoc($result)) {
$out .= "<tr><td>".$row["date"]."</td><td>".$row["select_bank"]."</td><td>".$row["entry_type"]."</td><td>".$row["income_cat"]."</td><td>".$row["expense_cat"]."</td><td>".$row["expense_cat_sub"]."</td><td>".$row["amount"]."</td></tr>";
}
}
}
I verified the database connection and it's working as expected. I also verified the variable $CurrMonth and $CurrYear values:
echo $CurrMonth; //will give output 10
echo $CurrYear; //will give output 2018
But I am not getting any search result. Any suggestions to resolve it?
The month and year comparison in your SQL looks incorrect, you are comparing the current month (and extracting the month from it MONTH(?)) with the month of the current date (MONTH(CURRENT_DATE())). You can get away without using any parameters as you need to compare (I assume) the month of the date from the record (MONTH(date)) with the current month (same for year).
$sql ="Select date,select_bank,entry_type,income_cat,expense_cat,
amount,expense_cat_sub
from wp_formdata
WHERE MONTH(date) = MONTH(CURRENT_DATE())
AND YEAR(date) = YEAR(CURRENT_DATE())
order by date ";
It's always worth checking SQL out in something like PHPMyAdmin to ensure it gives the results your after before running it in PHP.
In case you need to do this for any other month, you can use parameters, but don't extract the month from it...
$sql ="Select date,select_bank,entry_type,income_cat,expense_cat,
amount,expense_cat_sub
from wp_formdata
WHERE MONTH(date) = ?
AND YEAR(date) = ?
order by date ";
You are comparing the PHP current date to the DB current date.
In your SQL string you should replace MONTH(?) and YEAR(?) with MONTH(date) and YEAR(date).
At this point you should remove the mysqli_stmt_bind_param($stmt,"ss", $CurrMonth, $CurrYear); because the SQL string has not parameters.

How to Subtract current date time from date time in database - PHP

I'm working on a project.I have to check " how many minutes ago ,user updated the database " .For that I used following code :
<?php
include('connect_db.php');
$sql =" SELECT * FROM test_table WHERE user='john' ORDER BY time_ DESC LIMIT 1" ;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$time = strtotime($row['time_']);
$current=time();
$sub_time=$current-$time;
echo $sub_time;
}
The problem is the code is returning negative values like [ -17173 ].
The date-time stored in my db is like [ 2018-07-14 11:42:21.006515 ]
I simply want to compare current time with the the time stored in database get results in seconds or minutes .
I need help to solve this issue.Thank you .
You can just change your select statement to give you the time difference in seconds as shown below:
$sql =" select UNIX_TIMESTAMP(current_Timestamp()) - UNIX_TIMESTAMP(time_) FROM test_table WHERE user='john' ORDER BY time_ DESC LIMIT 1" ;
I think DateTime is better approach, as it has the methods to achieve the result you need.
maybe something like this:
$time=$row['time_'];
$curr_time=new DateTime();
$difference=$time->diff($curr_time);
http://php.net/manual/en/class.datetime.php
Updated
You should use the DateTime functions to figure out the difference in time. You should be able to integrate this into your code.
I incorporated my suggested code as a function into your original code. This should work for you.
Try this:
function timeDiff($date){
$date = new DateTime(date('Y-m-d H:i:s', strtotime($date)));
$current = new DateTime(date('Y-m-d H:i:s'));
$interval = $date->diff($current);
return $interval->format('%H:%I:%S');
}
include('connect_db.php');
$sql ="SELECT * FROM test_table WHERE user='john' ORDER BY time_ DESC LIMIT 1" ;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo timeDiff($row['time_']);
}
}
You first need to convert them to timestamp. And them subtract them convert the resuting timestamp back to format you want.
while($row = $result->fetch_assoc()) {
$time = strtotime($row['time_']);
$current=time();
$sub_time=date('d-m-y h:i:s',(strototime(date('d-m-y h:i:s')-$time));
echo $sub_time;
}
You need to handle the greater than and less than cases too.

SQL query TIMESTAMPDIFF with php not working

I try to take a date and do countdown untill that day like following:
The date i want to countdown to: 2016-05-1 00:00:00
Then i want to calculate the diff between the date and now so i can do countdown timer.
I have this:
date_default_timezone_set("Asia/Jerusalem");
if ($result = $db->query("SELECT TIMESTAMPDIFF(SECOND, NOW(), 2016-05-1 00:00:00)")) {
while($row = $result->fetch_array()) {
$currentTimeLeft= $row['TIMESTAMPDIFF(SECOND, NOW(), 2016-05-1 00:00:00)'];
}
echo json_encode($currentTimeLeft);
}
I dont understand why this returning empty. What is wrong here?
I see quote issue in your query
try this
if($result = $db->query("SELECT TIMESTAMPDIFF(SECOND,NOW(),'2016-05-1 00:00:00') as datediff")) {
while($row = $result->fetch_array()) {
$currentTime = $row['datediff'];
}
echo json_encode($currentTime);
I have added an alias "datediff" to the result column as well
you are missing quotes in the query
if ($result = $db->query("SELECT TIMESTAMPDIFF(SECOND, NOW(), '2016-05-1 00:00:00') as t")) {

Mysql Text to Date won't work

I got the following problem. I got a mysql field which is type "text" and there are many birthday dates in it.
I want to print the dates out and sort it in my way of date format. I can't change the type in the database because it's related to some user profile value fields.
The value's thats in the database are such this:
1978-12-31 23:59:59
This is my query:
$result = mysql_query("SELECT a.value, b.username from yrt6h_community_fields_values a join yrt6h_users b on a.user_id = b.id where a.field_id = 3 order by a.value;");
And this my example php file:
<table>
<tr>
<td>User:</td>
<td>Datum:</td>
</tr>
<?php
while($row = mysql_fetch_array($result)){
echo '<tr>';
echo '<td>';
echo $row['username'] . ' : ';
echo '</td>';
echo '<td>';
echo $row['value'];
echo '</td></tr>';
}
?>
</table>
I tried all of the date format functions of mysql, but then i got nothing.
For example I tried this:
mysql_query("SELECT str_to_date(a.value, '%d.%m.%Y'), ...
or
mysql_query("SELECT str_to_date(date_format(a.value, '%Y.%m.%d') %d.%m.%Y), ...
But I do that, the echo of the date is empty. Theres nothing to print out anymore. But why? Even if I put this query directly in the database I got NULL for the birthday value.
why dont you try to do it with php like -
echo date('d-m-Y', strtotime($yourDate));//the first paramete is the date format you want and the second is the value you are getting from database.
Reference for more understanding, example and formats.
Almost there!
I would suggest that you first get the data from the db with
mysql_query("SELECT str_to_date(a.value, '%d.%m.%Y')
Then
while($row = mysql_fetch_array($result))
{
$date = $row['date'];
$time = strtotime($date);
$formattedDate = date('Y-m-d', $time);
}
echo $formattedDate ;
Does that make senese?
Have you tried the PHP Date() function?
You could do something like so:
If you're looking for all records that match a specific date:
$timestamp = date('Y-m-d H:i:s'); //get current timestamp
mysql_query("SELECT * FROM `table` WHERE `timestamp` = '$timestamp'");
Or -- If you're trying to select/order by Timestamp:
mysql_query("SELECT * FROM `table` ORDER BY `timestamp`"); //select all order by timestamp
you can use mysql "cast" function.
rewrite the query in such a way:
"SELECT cast(a.value as DATETIME) new_dob,str_to_date(a.value, '%d.%m.%Y') dob from table_nm where cond"

Categories