MySQL - Compare all values in a column and write in another column - php

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.

Related

PHP/mySQL get time difference by x seconds

My goal is to get the time difference between 2 different times, one from my database, and one from the client's PHP timestamp, and compare them. Then, if the time difference is less than or equal to 10 seconds, then do something.
My code, which does not work, is as follows.
date_default_timezone_set('America/Chicago');
$timestamp = date('Y-m-d H:i:s');
$sqlcheck = $dbh->prepare("SELECT timestem FROM mytable WHERE UNIX_TIMESTAMP(timestem) - UNIX_TIMESTAMP('".$timestamp."') <= 10");
$sqlcheck->execute();
if ($sqlcheck === ''){
echo "Yes";
}
else {
echo "No";
}
timestem is a DATETIME value from mySQL. $sqlcheck is meant to portray the result of the query. If the query returns nothing, then echo Yes. If it returns something from my query, then echo No.
Without getting too convoluted in explanation, my end-goal is to check how long it has been since a database operation before a client is allowed to perform updates.
You should use the MySQL built-in TIMESTAMPDIFF function:
$sqlcheck = $dbh->prepare('SELECT timestem FROM mytable WHERE TIMESTAMPDIFF(SECOND, timestem, $1) <= 10');
$result = $sqlcheck->execute([$timestamp]);
Note that instead of concatenating strings, I am providing the $timestamp as a parameterized argument.
To check the result, you can't just check for string equality. Instead, use fetchColumn on the result object:
if ($timestem = $result->fetchColumn()) {
echo "YES";
// You can also use the value of `$timestem` here.
} else {
echo "NO";
}
Note that this assumes there is only one row. For multiple rows, you need a loop. Note that only rows that match the condition are returned, so you will never see any NO output if you use a loop.
You can just as easily do the check in PHP (which will probably be a bit more straight-forward)
$sqlcheck = $dbh->prepare( "SELECT timestem FROM mytable" );
$sqlcheck->execute();
// You missed this step
$timestem = $sqlcheck->fetchColumn();
if ( time() - strtotime( $timestem ) > 10 )
print 'yes';
else
print 'no';
Some notes:
In your code you didn't actually get the value out of the database. You used the result object in your conditional
Your code implicitly assumes there is only ever one record in your table. This probably isn't true: you will need a where condition
You have to be very certain that all of your timestamps are in the same time zone
This will only work if you are using PDO, not mysqli. I can't tell the difference from your example, but a subtle difference is that PDO will allow you to use a prepare and execute with no bound parameters, but mysqli won't.

PHP : comparing fetched date with today

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.

How could I echo a random database field once a week using php and mySQL?

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.

If statement to check if existing entry is in database

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'];

PHP: mysql_fetch_array() in a while-loop takes too long

I am creating an online calendar for a client using PHP/MySQL.
I initiated a <table> and <tr>, and after that have a while loop that creates a new <td> for each day, up to the max number of days in the month.
The line after the <td>, PHP searches a MySQL database for any events that occur on that day by comparing the value of $i (the counter) to the value of the formatted Unix timestamp within that row of the database. In order to increment the internal row counter ONLY when a match is made, I have made another while loop that fetches a new array for the result. It is significantly slowing down loading time.
Here's the code, shortened so you don't have to read the unnecessary stuff:
$qry = "SELECT * FROM events WHERE author=\"$author\"";
$result = mysql_query($qry) or die(mysql_error());
$row = mysql_fetch_array($result);
for ($i = 1; $i <= $max_days; $i++) {
echo "<td class=\"day\">";
$rowunixdate_number = date("j", $row['unixdate']);
if ($rowunixdate_number == $i) {
while ($rowunixdate_number == $i) {
$rowtitle = $row['title'];
echo $rowtitle;
$row = mysql_fetch_array($result);
$rowunixdate_number = date("j", $row['unixdate']);
}
}
echo "</td>";
if (newWeek($day_count)) {
echo "</tr><tr>";
}
$day_count++;
}
The slowness is most likely because you're doing 31 queries, instead of 1 query before you build the HTML table, as Nael El Shawwa pointed out -- if you're trying to get all the upcoming events for a given author for the month, you should select that in a single SQL query, and then iterate over the result set to actually generate the table. E.g.
$sql = "SELECT * FROM events WHERE author = '$author' ORDER BY xdate ASC";
$rsEvents = mysql_query($sql);
echo("<table><tr>");
while ($Event = mysql_fetch_array($rsEvents)) {
echo("<td>[event info in $Event goes here]</td>");
}
echo("</tr></table>");
Furthermore, it's usually a bad idea to intermix SQL queries and HTML generation. Your external data should be gathered in one place, the output data generated in another. My example cuts it close, by having the SQL immediately before the HTML generation, but that's still better than having an HTML block contain SQL queries right in the middle of it.
Have you run that query in a MySQL tool to see how long it takes?
Do you have an index on the author column?
There's nothing wrong with your PHP. I suspect the query is the problem and no index is the cause.
aside from their comments above, also try to optimize your sql query since this is one of the most common source of performance issues.
let say you have a news article table with Title, Date, Blurb, Content fields and you only need to fetch the title and display them as a list on the html page,
to do a "SELECT * FROM TABLE"
means that you are requiring the db server to fetch all the field data when doing the loop (including the Blurb and Content which you are not going to use).
if you optimize that to something like:
"SELECT Title, Date FROM TABLE" would fetch only the necessary data and would be more efficient in terms of server utilization.
i hope this helps you.
Is 'author' an id? or a string? Either way an index would help you.
The query is not slow, its the for loop thats causing the problem. Its not complete; missing the $i loop condition and increment. Or is this a typo?
Why don't you just order the query by the date?
SELECT * FROM events WHERE author=? ORDER BY unixdate ASC
and have a variable to store the current date you are on to have any logic required to group events by date in your table ex. giving all event rows with the same date the same color.
Assuming the date is a unix timestamp that does not account for the event's time then you can do this:
$currentDate = 0;
while(mysql_fetch_array($result)){
if($currentDate == $row['unixdate']){
//code to present an event that is on the same day as the previous event
}else{
//code to present an even on a date that is past the previous event
//you are sorting events by date in the query
}
//update currentDate for next iteration
$currentDate = $row['unixdate'];
}
if unixdate includes the event time, then you need to add some logic to just extract the unix date timestmap excluding the hours and minutes.
Hope that helps

Categories