Data is not Found from Database in PHP - 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
}
?>

Related

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 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}";

MySQL INNER JOIN with date as condition

I'm trying to use inner join to get the data from two tables using date as one of the condition. But since the second table contain dateTime column type, I want to use only the date to check for condition. When i run the code using Postman, it says I have error in SQL syntax at line (DATE)checkInDateTime = $rideDate . I also have test the SQL without taking the date into condition and the SQL works . Is there any ways to use the date as condition in InnerJoin method? Please help me . Thanks.
P/s : my dateTime column store values such as 2015-01-08 11:18:02
//get all rides from table rides
$result = mysql_query("SELECT first.ID, first.fullname,
second.checkInDateTime FROM first INNER JOIN second ON first.ID =
second.riderID WHERE second.ridesID = $rideID AND second.
CAST(checkInDateTime AS DATE) = $rideDate") or die(mysql_error());
//check for empty result
if(mysql_num_rows($result) > 0) {
//loop all result and put into array riders
$response["riders"] = array();
while ($row = mysql_fetch_array($result)) {
//temp array
$rider = array();
$rider["riderID"] = $row["ID"];
$rider["riderName"] = $row["fullname"];
$rider["timeCheckedIn"] = $row["checkInDateTime"];
//push single ride into final response array
array_push($response["riders"], $rider);
}
//success
$response["success"] = 1;
//print JSON response
echo json_encode($response);
} else {
//no rides found
$response["success"] = 0;
$response["message"] = "No riders found";
//print JSON response
echo json_encode($response);
}
I'm guessing the (DATE)checkInDateTime is an attempt at typecasting, and you're getting the sql error because that's not the right syntax... try CAST(checkInDateTime AS DATE) instead.

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