Trying to figure out why my code isn't working. Basically I have an elseif statment like so:
mysql_connect("localhost","xxxx","xxxxx");
mysql_select_db("xxxxxx");
$sql = "SELECT COUNT(DATE) FROM calendar";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
$checkdate = $row['DATE'];
$DATEFROM = $_POST['DATEFROM'];
$DAYCOUNT = $_POST['DAYCOUNT'];
$DAYS = $_POST['DAYS'];
if ( $DAYCOUNT < $DAYS ) {
header( 'Location: request_go_fail.php' );
}
else if ( $checkdate == $DATEFROM ) {
echo "FAIL!";
}
else {
It doesn't work, the first check (to see if the DAYCOUNT is less than DAYS works fine, but when comparing to entries in the DB it doesn't seem to do it. Seems to be some issue with finding the already existing data, as when I change $checkdate to an entry that's already in the database it works great.
Any help is most appreciated :)
SELECT COUNT(DATE) FROM calendar doesn't return a field called date, print_r the $row variable to confirm that. Best solution is to change the statement to something like SELECT COUNT(DATE) AS datecount FROM calendar and then do $checkdate = $row['datecount'];
But while rereading your code fragment, I'm not sure that you really want the count of DATE's in the calendar table, and what exactly the intention is, is hard to determine from the code fragment.
Also, DATE is a reserved word in SQL, not the optimal choice for a column name!
Did you try printing $checkdate? I suspect it's null if that is indeed the SQL you're using.
Should be $row['COUNT(DATE)'] I believe, or you can use mysql_fetch_array and $row[0] instead, or use an AS in your SQL or
$checkdate = mysql_result($result, 0);
And skip the fetch call all together.
COUNT(DATE) will return the number of non-null DATE fields in your DB btw, is that really what you want?
You don't have a DATE key in the $row variable because of the sql command. Use this instead, it's called Alias:
SELECT COUNT(DATE) AS DATE_COUNT FROM calendar
Now you have a key DATE_COUNT which will contains value.
$checkdate = $row['DATE_COUNT'];
Related
I have a PHP query to display the time an order was inserted on the database but all I'm getting in return is the current time not what I have on the database table.
public function count_todayorder(){
$today_date = date("m-d-Y");
$query="SELECT * FROM set_order_detail WHERE order_placed_date LIKE '%$today_date%'";
$con=Utility::DB_Connection();
mysqli_set_charset($con,'utf8');
$result=mysqli_query($con,$query);
$count=mysqli_num_rows($result);
return $count;
}
To display the table I'm using this.
<div>
<b>Ordered date:</b>
<?php date_default_timezone_set('America/New_York');
echo $today_date = date('g:i:s A - m-d-y ');
?>
</div>
It seems you are not actually using the date from the database, but rather you are just using the date function without setting the timestamp.
This is the date() functions syntax: date(format,timestamp);
So using your code, it would be:
date('g:i:s A - m-d-y ', $dateFromDB);
You just need to get the date from the database, and add it to the date() function where $dateFromDB is.
Try to change this date formate
Database date formate is yyyy-mm-dd.
So you should change your current date formate like below:
$today_date = date("Y-m-d");
$query='SELECT * FROM set_order_detail WHERE order_placed_date LIKE "%'.$today_date.'%"';
To tackle the problem you need to firstly understand that you have 2 different servers. One for the PHP and one for the database-in your case MySQL. Latter server will store records based on the time_zone stored variable. By default that should be set to SYSTEM -if you haven't tempered with the settings.
To check that perform the following query SELECT ##time_zone;. In case that it is something like +00:00 it is equal to GMT. Alternatively try SHOW VARIABLES LIKE 'time_zone';
Thus, for integrity purposes, you should always rely on what your SQL server provides. Lets amend the select statement to;
$query="SELECT * FROM `set_order_detail` WHERE DATE( `order_placed_date` ) = DATE( NOW( ) )";
...and remove the $today_date = date("m-d-Y"); part which, is not needed at all.
I assume that order_placed_date is either DATETIME or TIMESTAMP since you haven't placed a data-set example.
Given query will return the date format which by default is 'YYYY-MM-DD'. Casting this into PHP via date function will re-evaluate it based on the PHP server clock, which is a non-go. To get the proper format you need something like this
SELECT *, DATE_FORMAT( `order_placed_date`, '%l:%i:%s %p - %c-%e-%y') AS `format` FROM `set_order_detail` WHERE DATE( `order_placed_date` ) = DATE( NOW( ) );
Please check MySQL DATE_FORMAT function for more details.
To continue, your function -like #Barmar wrote in a comment- returns the number of rows matched and not the content fetched via the query. Therefore, the function should look something like that.
// somewhere in your class add this
public function todayOrders( )
{
$query="SELECT *, DATE_FORMAT( `order_placed_date`, '%l:%i:%s %p - %c-%e-%y') AS `format` FROM `set_order_detail` WHERE DATE( `order_placed_date` ) = DATE( NOW( ) );";
$con=Utility::DB_Connection();
mysqli_set_charset($con,'utf8');
$result=mysqli_query($con,$query);
if( !is_resource( $result ) )
{
return [];
}
$rows = [];
while( $row = mysqli_fetch_row( $result ) )
{
$rows[ ] = $row['format'];
}
return $rows;
}
Note: do not replace your previous method, just append this one, in case there are errors on this method. I am not able to test it atm.
To conclude and to produce the set of results fetched via the db in your template try the following.
<?php $rows = todayOrders( ); ?>
<?php foreach( $rows as $today_date ) : ?>
<div>
<b>Ordered date:</b> <?php echo $today_date; ?>
</div>
Hope it helped.
i'm saving time for first login ,now when user logs in i enter time using NOW() function, that saves time in this format (data type is DATETIME.
2015-12-24 15:47:30
Now logic is like every login is first login so i've to check if there already exists an entry for today to check that i fetch time explode it and get time like this
$logintime= mysqli_query($connection,"SELECT loggedin from employees");
$loggedin_time= mysqli_fetch_assoc($logintime);
$Date = $loggedin_time['loggedin'];
$loggedin_time_converted= explode(" ",$yourDate) ;
$ConvertedDate = $loggedin_time_converted[0];
last line returns 2015-12-24 now i've date
$today= time();
$DateToday= date("Y-m-d",$today);
$DateToday also returns me same format and same date now i need your help me to compare these dates , if they are equel i dont uopdate database if they are not i will , Pleas help me how do i compare these values
You can do the test in MySQL
$result = mysqli_query($connection, "SELECT DATE(loggedin) = CURDATE() AS logged_in_today FROM employees");
$row = mysqli_fetch_assoc($result);
if (!$row['logged_in_today']) {
// code to update database
}
Wow, you've done all the hard stuff to get the problem to the point of being a simple comparison of 2 strings. This is all you need to do to get over the finish line ...
if ($ConvertedDate !== $DateToday) {
// update the database
}
You can use Php Built In function "Date Difference."
Code Seems Like As Follow:-
$today= time();
$DateToday= date("Y-m-d",$today);
$diff = date_diff($today,$DateToday);
echo "$diff days";
This will return values something like +12 days or something else.
I am trying to get all rows in a database which have been created between two dates inclusively. When I search for meetings in 2013-05-01 and todays date, I get no results but when I search without the WHERE clause I see there are two records for today. I thought, since the dates are DATETIME, I would try casting them as dates but this doesn't seem to work.
My function is as follows:
function meeting_reports($connection, $to, $from)
{
$status = array();
$sql =
$connection->query (
"SELECT `meeting_id`,`visibility`,`meeting_start`
FROM `details`
WHERE DATE(`meeting_start`) BETWEEN '{$from}' AND '{$to}'"
);
$status["total_meetings"] = 0;
$status["cancelled_meetings"] = 0;
if($sql->num_rows > 0)
{
while($results = $sql->fetch_assoc())
{
if($results["visibility"]==0)
{
$status["total_meetings"]++;
}
elseif($results==1)
{
$status["total_meetings"]++;
}
elseif($results["visibility"]==2)
{
$status["total_meetings"]++;
}
elseif($results["visibility"]==3)
{
$status["cancelled_meetings"]++;
}
}
}
return $status;
}
What am I doing wrong?
I see a couple issues here.
you need to clarify if your data type is date, or datetime. going to assume datetime.
also if you are looking for meetings that occurred on a single specific day,
you cannot search for events between x and y if x=y. there is nothing between
it. if you are using datetime date type, concat 00:00:00 to your start date
and 23:59:59 to your end date, now you have a valid range that includes the the valid times for the date in question. or for single date searches, do between ? and ? + interval 1 day and pass date twice as '12-25-2015 00:00:00'
also, you are directly using strings in your query, this can open you up to
sql injection attacks. do a google search on bound parameters and never use
a variable in an sql query EVER again.
Try this
$connection->query (
"SELECT meeting_id,visibility,meeting_start
FROM details
WHERE meeting_start BETWEEN '" . $from . "' AND '" . $to . "'"
);
I need to create a script that compares one field in the database (has a date stored, it's type is "TEXT" and cannot be changed DATE) to the current server date.
The dates are encoded like this "1380571547", so i need to use strftime() to decode them. This field for example, decoded with strftime corresponds to this "Sep-30-2013, 22:05"
What I need is to compare those fields with the current date, and according to that condition, write something like "Expired" in another field.
To achieve this, I made this block of code:
<?php
require("connection.php");
$today = strftime('%b-%d-%Y, %H:%M');
$exp_date = mysql_query("SELECT numbers FROM date");
while($row = mysql_fetch_array($exp_date))
{
echo (strftime ( '%b-%d-%Y, %H:%M', $row ['numbers'])). "<br />";
}
if ($exp_date < $today) {
$sql = "INSERT INTO date (changed) VALUES ('EXPIRED')";
$result = mysql_query($sql);
echo "ADDED!";
}
?>
However, this code is not working, can someone help me ?
PHP is not my strong point but it looks to me like you condition is doing a comparison on an array,
IE:
if ($exp_date < $today) // will always be false.
Your code would probably have to look something more like this.
while($row = mysql_fetch_array($exp_date))
{
if ($row[0] < $today)
{
$sql = "Update date set changed = VALUE where rowid = rowid";
$result = mysql_query($sql);
echo "ADDED!";
}
}
having said that i would probably do the comparison and update in SQL using a case statement,
Update Date
set changed = case when number > ExpiryDate
then "Expired"
else "Current"
end
You can do all this in a single query:
UPDATE `date` set `changed`='Expired' where date(now()) > date(from_unixtime(`numbers`))
But this is not what your code is attempting to do. Your second block seems to be inserting the word Expired in new rows, rather than updating anything.
Note that the table name date should be wrapped in backticks to avoid any possible clash with MySQL keywords
I don't understand the second block of code with the insert. I would do an update inside the loop. but if your going to do that, it could probably be done in one combined update statement.
Google hasn't been much help sadly. I have some pseudo code below to give you an idea of what I'd like to achieve:
if ($time == one week) {
$result = mysql_query("SELECT * FROM table RANDOMLY,$connection");
echo $result[0];
}
I know I should be using mysqli, but I'm augumenting an existing (ageing) system. I'll be utilising mysqli in future, so if you could give me the solution using mysql that would be great!
I don't think it can be done with a single statement.
My best guess would be to use mysql_list_tables, select a random entry from that list and continue from there on.
Perhaps generating a random number between 1 and the value of SELECT Count(ID) from table. Then you have the index of the value you wish to output, you can simply run a SELECT statement for it; and output! :)
if ($time == one week) {
$result = mysql_query("SELECT * FROM table RANDOMLY,$connection");
echo $result[0];
}
Try this:
$weekNumber = date("W");
$result = mysqli_query("SELECT * FROM table RANDOMLY WHERE weeknumber = '\"$weekNumber\"', $connection");
echo $result[0];
}
Of course you’ll need a column in your table called weeknumber with 1 through 52 setup ahead of time.
As others pointed out you shouldn’t use mysql_* anything. I changed it to a mysqli_query.