Display event name from database in current date.
This is my code:
<?php
$insum=mysql_query("SELECT * FROM `log` AS event_today WHERE `date` = $currentdate");
$d=mysql_fetch_assoc($insum);
$query = mysql_query("SELECT * FROM log");
$number=mysql_num_rows($query);
?>
<div class="inner">
<h3>
<?php
echo " {$d['event_today']} / ";
echo $number;
?></h3>
</div>
To get the date in a format that MySQL can understand (YYYY-MM-DD), use:
$currentdate = date('Y-m-d');
You also should use MySQLi rather than mysql_*(), as the old mysql_*() functions are now deprecated.
$currentdate needs to quoted, and in a yyyy-mm-dd format
So
$insum=mysql_query("SELECT * FROM `log` AS event_today WHERE `date` = '$currentdate'");
Note, this method of MySQLing has been depracated in place of PDO or mysqli
Related
This question already has answers here:
Single result from database using mysqli
(6 answers)
How to get count of rows in MySQL table using PHP?
(3 answers)
Closed 2 years ago.
I use the same query to return one integer value between two dates which is a sum of column
SQL Query:
SELECT SUM(TransactionAmount) FROM `sales` WHERE TransactionTime BETWEEN '2020-12-15' AND '2020-12-16'
In this PHP Code:
<?php
require 'config/db.php';
if(isset($_POST["searchinDate-btn"])){
$start_date = $_POST['startdate'];
$end_date = $_POST['enddate'];
$totalRev = "SELECT SUM(TransactionAmount) FROM `sales` WHERE TransactionTime BETWEEN '$start_date' AND '$end_date'";
$totalRevQ = mysqli_query($conn, $totalRev);
$rev = mysqli_fetch_assoc($totalRevQ);
$revenue = $rev[0];
}
?>
(Additional) HTML Code:
<form action="Dashboard.php" method="POST">
<div class="dateselect">
<label for="start-date">Start Date: </label>
<input type="date" id="start-date" name="startdate" value="">
<label for="start-date"> - - End Date: </label>
<input type="date" id="end-date" name="enddate" value="">
<button style="margin-bottom: 3px;" type="submit" name="searchinDate-btn" class="mbtn btn btn-primary">Show</button>
</div>
</form>
<p> <?php echo $revenue; ?> </p>
The Variable revenue return nothing for some reason!
Note: Both start date and end date and the query result actually return results but I think there is a problem with showing the result of the query which will be one integer value like 562 or something else! ( I need the value of the row number 0 not the count of the rows)
UPDATE: The wrong was in passing date type from PHP to compare it with timestamp field type at the database.
to convert date to time stamp I use this PHP Code:
<?php
require 'config/db.php';
if(isset($_POST["searchinDate-btn"])){
$start_date = $_POST['startdate'];
$StartDate = date("Y-m-d H:i:s", strtotime($start_date));
$end_date = $_POST['enddate'];
$EndDate = date("Y-m-d H:i:s", strtotime($end_date + '24 hours'));
$totalRev = "SELECT SUM(TransactionAmount) AS Revenue FROM `sales` WHERE TransactionTime BETWEEN '$StartDate' AND '$EndDate'";
$totalRevQ = mysqli_query($conn, $totalRev);
$rev = mysqli_fetch_assoc($totalRevQ);
$revenue = $rev['Revenue'];
}
?>
Because you used mysqli_fetch_assoc function you need to set a name for the result (I this name to "AmountSum" in my example):
<?php
require 'config/db.php';
if(isset($_POST["searchinDate-btn"])){
$start_date = $_POST['startdate'];
$end_date = $_POST['enddate'];
$totalRev = "SELECT SUM(TransactionAmount) AS AmountSum FROM `sales` WHERE TransactionTime BETWEEN '$start_date' AND '$end_date'";
$totalRevQ = mysqli_query($conn, $totalRev);
$rev = mysqli_fetch_assoc($totalRevQ);
$revenue = $rev['AmountSum'];
}
?>
Maybe adding an alias to the sum in the query:
$totalRev = "SELECT SUM(TransactionAmount) AS totalAmount FROM `sales` WHERE TransactionTime BETWEEN '$start_date' AND '$end_date'";
Then changing $rev = mysqli_fetch_assoc($totalRevQ) to $rev = mysqli_fetch_array($totalRevQ), in order to get the value with $revenue = $rev["totalAmount"] :D
Also, as Strawberry said, don't forget to protect that query from SQL injection, it's never good to trust user input!
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.
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"
I have a mysql database.
I have a php script, that connects to my database. My database consists of 3 tables, error, date, email address, as per the screenshot
my php query is as follows:
<?php
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("pmta_reporting") or die(mysql_error());
$result = mysql_query("SELECT * FROM microcompany WHERE date='2013-01-28' AND code='2.0.0'") or die(mysql_error());
$count= mysql_num_rows($result);
echo $count;
mysqli_close($con);
?>
I would like to replace '2013-01-28' with yesterdays date and in that format Y-m-d.
How can I do this?
Any feedback would be appreciated
$yesterday = date("Y-m-d", strtotime('-1 day'));
$result = mysql_query("SELECT * FROM microcompany WHERE date='$yesterday' AND code='2.0.0'") or die(mysql_error());
Why not use the MySQL function? They are meant to be used in MySQL.
SELECT * FROM microcompany WHERE date=DATE(DATE_SUB(NOW(), INTERVAL 1 DAY)) AND code='2.0.0'
btw. mysql-* functions are deprecated: http://www.php.net/manual/en/function.mysql-query.php
$date = new DateTime('Yesterday');
echo $date->format('Y-m-d');
Or
$date = new DateTime('2013-01-28');
$date->modify('-1 day');
echo $date->format('Y-m-d');
FYI, you shouldn't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
use native mysql functions for that purpose.
$result = mysql_query("SELECT * FROM microcompany WHERE
date=date_sub(date(now()), interval 1 day) AND code='2.0.0'")
or die(mysql_error());
$date = new DateTime('Yesterday');
$fdate = $date->format('Y-m-d');
echo $fdate;
<?php
$yesterday = date('Y-m-d', strtotime('-1 day',strtotime(date("y-m-d")) ));
$query = "SELECT * FROM microcompany WHERE date='".$yesterday."' AND code='2.0.0'";
$newQuery = 'update microcompany set date = "'.$yesterday.' where date = "'.$oldDate.'" and code ="2.0.0"';
?>
I am using mysql and php to pull all the users out of the mysql database that are equal to todays date. The problem I am having is whenever I run the following code I get an error. By the look of the error is seems to be something to do with the year, or maybe it doesn't like the dots in it, but im not sure ?.
<?php
$today = date("d.m.y");
$result = mysql_query("SELECT * FROM ymeg_chronoforms_data_NewsletterSubscribe
WHERE date=$today")or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row['name'] . " " . $row['email']. " " . $row['date'];
echo "<br />";
}
?>
This is the error it is throwing :
You have an error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near '.12' at line 2
You have to add quotes around your date string:
$result = mysql_query("SELECT * FROM ymeg_chronoforms_data_NewsletterSubscribe
WHERE date='$today'")or die(mysql_error());
Need quotes around your $today variable. Also need to backtick the date column name since it's reserved.
$result = mysql_query("SELECT * FROM ymeg_chronoforms_data_NewsletterSubscribe
WHERE `date`='$today'")or die(mysql_error());
First of all, $today should be added as a string into the SQL query:
mysql_query("SELECT * FROM ymeg_chronoforms_data_NewsletterSubscribe WHERE `date` = '$today'");
date is a SQL reserved word so it has to be escaped with backticks...
But I recomment using MySQL native functions and constants like NOW(), CURRENT_TIMESTAMP, SYSDATE etc...
SELECT * FROM ymeg_chronoforms_data_NewsletterSubscribe WHERE `date` = NOW()
SELECT * FROM ymeg_chronoforms_data_NewsletterSubscribe WHERE `date` < NOW() - INTERVAL '2' DAYS
SELECT * FROM ymeg_chronoforms_data_NewsletterSubscribe WHERE `date` > NOW() + INTERVAL '5' HOURS
etc...
if you are using timestamp as datatype in mysql then you need to convert the date into unix timestamp first.
$today = strtotime("now");
or if you are using datetime or date data type then correct format is
YY-MM-DD, so you need to create the date accordingly.
$today = ('Y-m-d');
and also in your query you are missing single quote.
"SELECT * FROM ymeg_chronoforms_data_NewsletterSubscribe WHERE date = '$today'"
however you can compare the date without using PHP's date function, directly using MYSQL NOW().
SELECT * FROM ymeg_chronoforms_data_NewsletterSubscribe WHERE date = NOW()
Try
$today = date("d-m-Y");
OR
$today = date("Y-m-d");
Also, check the format of date column is equal to the format of the return value of date().
If you have used DATETIME data type you may need to use matching format.
Also, wrap date value with single quotes...
$result = mysql_query("SELECT * FROM ymeg_chronoforms_data_NewsletterSubscribe
WHERE date = '" . $today . "'")