i have this code which permits me to retrieve all the information in which the timestamp regarding that information is equal to another date.
Here is the code:
$information="SELECT * FROM scheda_anagrafica WHERE FROM_UNIXTIME('time_inserted','%d-%m-%Y') = '" . $giorno_selcted. "'
";
$result1 = mysql_query($information) or die (mysql_error());
while( $row = mysql_fetch_array($result1)) {
echo $row['information1'];
}
giorno_selected prints something like: 25-09-2012
What am i doing wrong here?
Thanks!
first of all, you should not use mysql functions on the left hand side of a operator in a where clause. this way mysql needs to read the complete table on disk to compute the value to compare with instead of optimizing the query for speed and resource usage (IO, cpu).
from your question and comments i understand, that you are querying the database for rows which have the same day as the string in your $giorno_selected represents. so you need to find all rows with timestamps between 0:00 and 23:59 on that specific day:
$giorno_timestamp_start = date_create_from_format('d-m-Y', $giorno_selected)->getTimestamp();
$giorno_timestamp_end = $giorno_timestamp_start + 86399; //add almost all seconds per day onto the start timestamp
$information="SELECT * FROM scheda_anagrafica WHERE time_inserted BETWEEN " . $giorno_timestamp_start. " AND ". $giorno_timestamp_end;
$result1 = mysql_query($information) or die (mysql_error());
while( $row = mysql_fetch_array($result1)) {
echo $row['information1'];
}
this works if your time_inserted column is of type integer and holds unix_timestampds.
if it is of type datetime or timestamp you need to modify the query like this:
$information="SELECT * FROM scheda_anagrafica WHERE time_inserted BETWEEN FROM_UNIXTIME(" . $giorno_timestamp_start. ") AND FROM_UNIXTIME(". $giorno_timestamp_end .")";
Related
I am using the following SELECT script which successfully finds the values for $payer_email, reminder_date and sub_expire_date, but no data is being produced when I apply the commented out WHERE condition to the SELECT. The intention of the WHERE is to filter the values from the SELECT to only provide those values which point to the subscription expiry (sub_expire_date) thirty days ahead of time, but no values are derived when the values do exist.
Can anyone tell me why the SELECT fails upon the inclusion of the WHERE?
<?php
error_reporting(E_ALL ^ E_NOTICE);
include_once("../real_conn/real_i_conn.php");
$reminder_date = date("Y-m-d", strtotime("+30 days"));
echo $reminder_date . "<br><br>";
$sql = "SELECT sec_tblpurchased_secureareas.users_id,
sec_tblpurchased_secureareas.sub_expire_date,
DATE_ADD(sec_tblpurchased_secureareas.sub_expire_date, INTERVAL - 30
day) AS reminder_date, sec_tblusers.payer_email
FROM sec_tblpurchased_secureareas
INNER JOIN sec_tblusers ON sec_tblusers.recid =
sec_tblpurchased_secureareas.users_id";
//WHERE DATE_ADD(sec_tblpurchased_secureareas.sub_expire_date, INTERVAL- 30 day) = '". $reminder_date ."' ";
$result = mysqli_query($conni, $sql);
if ($result) {
// Return the number of rows in result set
$rowcount = mysqli_num_rows($result);
printf("Result set has %d rows.\n", $rowcount);
echo "<br><br>";
}
while ($num = mysqli_fetch_array($result)) {
//echo $num;
$payer_email = $num['payer_email'];
echo $num['payer_email'] . " <br>";
$reminder_date = $num['reminder_date'];
$reminder_date = date_create("$reminder_date");
echo date_format($reminder_date, "Y/m/d") . " remind<br>";
$sub_expire_date = $num['sub_expire_date'];
$sub_expire_date = date_create("$sub_expire_date");
echo date_format($sub_expire_date, "Y/m/d") . " expire<br><br>";
}
?>
Your code is very difficult to read, and the code you shared is invalid (the line before the commented out //WHERE line ends "; but the line after starts - 30 -- this absolutely won't compile.
That said, my best guess is that you're using DATE_ADD incorrectly. Check out the documentation on it here: https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add
Notice it returns a DATETIME, never a DATE. If you wrap it in a DATE() call, however, you might get what you want.
FWIW, I find this easier to read:
SELECT x.users_id
, x.sub_expire_date
, DATE_ADD(x.sub_expire_date, INTERVAL - 30 DAY) reminder_date
, u.payer_email
FROM sec_tblpurchased_secureareas x
JOIN sec_tblusers u
ON u.recid = x.users_id;
I think the problem has been solved, indirectly. It looks like I just had to use
DATE_SUB(sec_tblpurchased_secureareas.sub_expire_date, INTERVAL 30 day) AS reminder_date
instead of DATE_ADD with a negative day value. This give me the variable I need to trigger the CRON.
Thanks for your help.
I am using the following (assume I already plan to change these to mysqli at a later date and am aware of the insecurity of the queries used), to pull text strings from rows in one column in a MySQL table and the output in a browser would, ideally, be a randomly selected string from this column:
mysql_connect($host,$username,$password);
mysql_select_db($database) or die(mysql_error ());
$query="SELECT * FROM `tablename` ORDER BY RAND() LIMIT 0,1;";
$result=mysql_query($query);
$rows = array();
while($row = mysql_fetch_array($rs)) {
$rows[] = $row;
}
mysql_close();
$max = count($rows) - 1;
Using the following echo line to achieve the last bit in the browser:
echo $rows[rand(0, $max)][0] . " " . $rows[rand(0, $max)][1] . " " . $rows[rand(0, $max)][2] . " " . $rows[rand(0, $max)][3] . " " . $rows[rand(0, $max)][4]$
?>
I receive the error "PHP Notice: Undefined offset: 0 in script.php on line 19" in reference to this echo line (which, admittedly, was pieced together from other threads and tutorials, so I do not follow completely), however, I've since resolved all other errors logged and observed, so if possible, how can I amend this so the output is just a single row (the text within it) from the column?
Faster and better than using RAND()
$conn = mysqli_connect($host,$username,$password, $database);
if($conn->connect_errno > 0) {
die('Unable to connect to database [' . $conn->connect_error . ']');
}
$total_rows = 20; //Generate Random number. You could get $total_rows with a first query counting all rows.
$selected_row = mt_rand(0, $total_rows);
//$selected_row -= 1; //just in case you randomized 1 - $total_rows and still need first row.
//Use the result in your limit.
$query="SELECT * FROM `tablename` LIMIT $selected_row, 1;";
$result=$conn->query($query);
while($row = $result->fetch_assoc()) {
echo $row["columnname"];
}
Edit it from mysql to mysqli (on the fly). You would not want to use RAND() if your table is very large. Believe me!
In your SELECT-statement, you are telling the database to order the strings randomly. So just get the first one and echo it:
$row = mysql_fetch_array($rs)
echo $row['name_of_field_you_want_to_echo'];
You never define the variable $rs. Other than that...
If you are selecting the first items from a SQL query, you don't need to specify both the limit and top.
$result = mysql_query("SELECT * FROM `tablename` ORDER BY RAND() LIMIT 1");
Since that will ever return one row, you can use mysql_fetch_row
$row = mysql_fetch_row($result);
and then you can get the field from that row with
echo $row["column_name"];
I have uploaded a PHP script in the server. What it does is, that it keeps reading the DB (mySQL), and if the DATE_OF_MATCH and TIME_OF_MATCH (these are 2 fields in the mySQL db) is equal to the server time it will execute a message.
fields in the table: all are VARCHAR
ID, DATE_OF_MATCH, TIME_OF_MATCH, MATCH_NAME
One record from the MATCH table;
1 , 1/12/2012, 3:40, ManU vs Kaks
The problem is that, my select statement is wrong. My $theDateAndTime is returning 09:15:03PM and in the Database i am having 2 separate records for date and time. So how can i edit the select statement so could match the date and time against the $theDateAndTime (returned by the server)
The code:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
date_default_timezone_set('America/New_York');
$theDateAndTime = date("h:i:sA")."\n";
$result = mysql_query("SELECT * FROM MATCH where DATE_OF_MATCH=".$theDateAndTime." and TIME_OF_MATCH=".$theDateAndTime."");
while(true){
if(result!=null){
while($row = mysql_fetch_array($result))
{
echo $row['MATCH_NAME'] ;
echo "<br />";
}
}
}
mysql_close($con);
?>
I don't understand your question very well, but seems that you are trying to query for date and time in two different fields but you are only take the current time. I think you should try something like this:
<?php
$current_date = date('d/m/Y');
$current_time = date('h:i');
$result = mysql_query("SELECT * FROM MATCH where DATE_OF_MATCH=".$current_date." and TIME_OF_MATCH=".$current_time."");
Otherwise, you should not use mysql_* functions, use mysqli_* functions instead with prepared statements.
Create two separate variables for date and then time.
$the_date = date("n/j/Y");
$the_time = date("h:i:s");
$result = mysql_query("SELECT * FROM MATCH where DATE_OF_MATCH={$the_date} and TIME_OF_MATCH={$the_time}");
http://us3.php.net/manual/en/function.date.php
I have searched and searched for ways to do this but have found very limited information.
I have a MySQL table 'msgdb' that contains a field 'ttime' that is in the format double(25,8) (example row = 1352899856.95249200).
I need to routinely cleanup the table by removing any rows where the field 'ttime' is <= today's date -5 days.
These are the only two lines of code I could find related to double to time conversion but cannot get either to work.
SELECT ADDDATE(ADDDATE(ADDDATE('1899-12-31 00:00:00',FLOOR(ttime)), INTERVAL -1 DAY),INTERVAL(MOD(ttime,1)*86400)SECOND) AS TrueDate FROM msgdb
select date('1899-12-31 00:00:00'+ INTERVAL ttime * 24*3600 SECOND) as date from msgdb
I have tried first to display any rows that match the criteria using the code below, before I started using DELETE FROM to make sure I'm getting the correct results.
$query = "select date('1899-12-31 00:00:00'+ INTERVAL ttime * 24*3600 SECOND) as date from msgdb";
$result = mysql_db_query ($dbname, $query, $link);
while($row = mysql_fetch_array($result)) {
echo $row['date'];
echo '<br>';
}
and also
$query = "SELECT ADDDATE(ADDDATE(ADDDATE('1899-12-31 00:00:00',FLOOR(ttime)), INTERVAL -1 DAY),INTERVAL(MOD(ttime,1)*86400)SECOND) AS TrueDate FROM msgdb";
$result = mysql_db_query ($dbname, $query, $link);
while($row = mysql_fetch_array($result)) {
echo $row['TrueDate'];
echo '<br>';
}
but both are returning nothing.
UPDATE: Ok so by using this code:
$query = "select ttime from msgdb";
$result = mysql_db_query ($dbname, $query, $link);
while($row = mysql_fetch_array($result)) {
echo date('m-j-Y, H:i:s', $row[0]);
echo '<br>';
}
I am able to see it convert 'ttime' field from the stored value of 1352899856.95249200 to 11-14-2012, 07:30:56.
So how would I DELETE from the table all rows where ttime is <=now - 5 days?
Figuring out which records have a date before a point in time should be easy:
DELETE FROM table WHERE ttime <= DATE_SUB(NOW(), INTERVAL 5 DAY);
It might also be better to use UTC_TIMESTAMP() if you store all your times in UTC, which is the only sane way to do it.
This script uses php and mysql to compute a one minute rolling average to reduce the impact of outliers on the my data (one minute = 6 10-second rows). It computes everything correctly, but is not efficient enough to do more than 150 rows at a time. I'd like to do as many rows as I can at a time, possibly between 5-10,000 as my table is over 150,000 and I input approximately 8,000 rows per day.
Does anyone have any suggestions as to how I can make this script run more efficiently?
Thanks!
<?php
//connect to database
mysql_connect("localhost","user","password");//database connection
mysql_select_db("database");
$result = mysql_query("SELECT Timestamp FROM table");
if (!$result) {
die('Could not query:' . mysql_error());
}
//get number of rows in table
$resultA = mysql_query("SELECT * FROM table");
$num_rows = mysql_num_rows($result);
echo "There are $num_rows rows.</br>";
//select column to be averaged
$resultB = mysql_query("SELECT PortRPMSignal FROM table");
if (!$resultB) {
die('Could not query:' . mysql_error());
}
//set start equal to the first row you want to calculate the averages from, likely the first null row
$start = 5;
//calculate 1 minute average, the average is correct
for($i = $start; $i<$num_rows; $i++){
$output = mysql_result($result,$i);
$test = mysql_result($resultB,$i)+mysql_result($resultB,$i-1)+mysql_result($resultB,$i-2)+mysql_result($resultB,$i-3)+mysql_result($resultB,$i-4)+mysql_result($resultB,$i-5);
$test2 = $test/6;
$round = round($test2,4);
$temp = mysql_query("SELECT Timestamp FROM table");
if(!$temp){
die('Could not query:' . mysql_error());
}
//gets timestamp at row $i, and inserts new average value into that row in RPMAve column
$time = mysql_result($result,$i);
mysql_query("UPDATE table SET PortMinuteAveRPM = $round WHERE Timestamp = '$time'");
}
For starters, the initial "count" block here can be cleaned up by adding the COUNT() aggregate:
$resultA = mysql_query("SELECT * FROM table");
$num_rows = mysql_num_rows($result);
echo "There are $num_rows rows.</br>";
Change to:
$resultA = mysql_query("SELECT COUNT(*) FROM table");
$row = mysql_fetch_array($result);
$num_rows = $row[0];
echo "There are $num_rows rows.</br>";
That should speed things up considerably on its own. Without it, you're selecting all of the data from the table - a query that will only grow slower the more you put into the table.
For the averages you're computing, is there any logic required that can't be accomplished directly in a MySQL query? Something such as:
UPDATE table SET PortMinuteAveRPM=(SELECT AVG(PortRPMSignal) FROM table WHERE Timestamp BETWEEN '$startTime' AND '$endTime') WHERE TimeStamp='$endTime'
This may save you from looping through results, if it's plausible.
It sounds like you're trying to calculate an autoregressive moving average (ARMA) but there's numerous issues with your interpretation of your data and how you are capturing it.
If you've got a complete set of data (though your question implies that you don't), then work out what time interval contains the required amount of records and get it direct from the database, e.g.
SELECT a.timestamp as base, AVG(b.PortRPMSignal)
FROM table a, table b
WHERE b.timestamp BETWEEN a.timestamp AND a.timestamp+INTERVAL 6 HOUR
GROUP BY a.timestamp
If you want to thin out the datapoints, then try something like....
SELECT a.timestamp as base, AVG(b.PortRPMSignal)
FROM table a, table b
WHERE b.timestamp BETWEEN a.timestamp AND a.timestamp+INTERVAL 6 HOUR
AND DATE_FORMAT(a.timestamp, '%i%s')='0000'
GROUP BY a.timestamp
Although a better solution if you've not got a complete dataset but there's only a small amount of jitter would be to use the modulus of an auto-increment id to pick out fewer rows from 'a'
It's only a start, but you can bin this bit
//get number of rows in table
$resultA = mysql_query("SELECT * FROM table");
$num_rows = mysql_num_rows($result);
echo "There are $num_rows rows.</br>";
Because the following line
$resultB = mysql_query("SELECT PortRPMSignal FROM table");
...will give you a result set that you can use mysql_num_rows on.
Using the * in a query increases the load on the database.
In your for loop you then have this
$temp = mysql_query("SELECT Timestamp FROM table");
if(!$temp){
die('Could not query:' . mysql_error());
}
which means this query runs every time you loop and you're not even using the results.
I don't know if mysqli will give you better performance, but you should use it.