Get SQL table data for current month using prepared statement PHP - 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.

Related

Data is not Found from Database in PHP

Today or Current Date Birthday Date Retrieve From the Ms Access Database.Suppose Today Date is 03-08-2018. I passed value only Date and Month day = 03, Month = 08 and year is not Pass. So, I Retrieve Current day and month record.
Data Retrieve Query in PHP File.This Query Run in Ms Access database is Successfully and fetch current date Record but In PHP file Give Empty Data.
Passed data in url just Like this: localhost/Bi.php?Chhaprabhatha&mon=8&day=3
Its Give Result Like This: Resource id #4{"status":0,"0":[]}
Query is Run in Database its give Result and Successfully run.In this code give null data
Bi.php
<?php
if(isset($_REQUEST["Chhaprabhatha"]))
{
include 'Connection.php';
$mon = $_GET['mon'];
$day = $_GET['day'];
$sql = "select std_name, regno,standard,division
FROM(select RegNo,b.Standard,c.Division,std_name,DOB as BirthDayDate,contactno1 as contact, Year(DOB) AS OrderYear, month(DOB) AS OrderMonth,Day(DOB) AS OrderDay,a.YearID,IsActive
from ((std_reg as a inner join standardmaster as b on a.standard = b.stdid)
inner join divisionmaster as c on a.division = c.divisionid)
) as t where (t.OrderMonth = $mon AND t.OrderDay = $day and t.Isactive = true)";
echo $stmt = odbc_exec($conn, $sql);
$result = [];
do {
while ($row = odbc_fetch_array($stmt)){
$result[] = $row;
}
} while (odbc_next_result($stmt));
if(count($result)>0)
{
$result1['status']=1;//"Login successfully";
echo array_push($result1,$result);
}
else
{
//$result[]="null";
$result1['status']=0;//"Record not found";
array_push($result1,$result);
}
odbc_free_result($stmt);
odbc_close($conn); //Close the connnectiokn first
echo json_encode($result1); //You will get the encoded array variable
}
?>

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.

How to pass month and year in url

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

how can i get the sum of all the products in a certain month in mysql

i am trying to get all the sum of payments made in a specific month lets say from January - March in my website .
My table which is equipments has Money and Joined as columns but the Joined column has both date and time .
I want to use this approach if it is possible but this snippet is for sum of prize.
if (isset($_POST['moneyMade'])){
$moneyMade=0;
$query = "select SUM(Money) from users where Joined<='2016-11-01 00:00:00' and Joined>='2016-11-31 00:00:00'";
//if (!$query) { echo 'MySQL Error: ' . mysqli_error(); exit; }
//$query="select * from equipments ";
$result = mysqli_query($conn,$query);
while ($row = mysqli_fetch_assoc($result)){ /* Fetch a result row as an associative array */
/*while ($row = mysqli_result($result)){*/
$moneyMade +=$row['Money'];
}
echo "Money made for this month is ". $moneyMade;
}
How can i achieve this using php and some sql ?
Thank you.
Assuming that Prize is a numerical value, you could do something like the following.
$month = 'January';
$month_start = strtotime("first day of {$month}");
$month_end = strtotime("last day of {$month}");
$query = "SELECT SUM(`Prize`) FROM `equipments` WHERE UNIX_TIMESTAMP(`Joined`) >= {$month_start} AND UNIX_TIMESTAMP(`Joined`) <= {$month_end}";

Show each if value is 0 show once if year is set PHP Calendar

I have made an event calandar and i give my users an option when they add an event to: Show each year? With and checkbox.
So if checkbox is checked I insert an 0 as year in my database if the checkbox is not checked I insert the actual date in the database.
http://i44.tinypic.com/2cdd1zm.png
But how can i show it on my calander each year if the value of year = 0;
BTW jaar = year.
//for showing once
if (Syear != 0){
$sqlEvent = "SELECT titel,content FROM **** WHERE `maand` = '$month' AND `dag` = '$day' AND '$year' = `jaar`";
$resultEvents = mysql_query($sqlEvent);
}
//for showing every year
else
{
$sqlEvent = "SELECT titel,content FROM *** WHERE `maand` = '$month' AND `dag` = '$day'";
$resultEvents = mysql_query($sqlEvent);
}
echo "<hr>";
// show event
while ($events = mysql_fetch_array($resultEvents)){
echo "Title: ".$events['titel']."<br>";
echo "Detail: ".$events['content']."<br>";
echo $year;
}
Thank you,
It looks like you just need to pull the years back from your database in addition to the title and content. So if you change both of the queries to do something like SELECT titel,content,jaar then each retrieved row will also include the year.
Then you can change echo $year to echo $events['jaar'].

Categories