strange mysql behaviour on timestamp - php

Please have a look at this mysql query. What it should do is pretty simple - list dates, created from timestamps not older than 10 days.
It works, but not perfectly ...
If I have only 1 timestamp matching, I have 0 results.
If I have 2 timestamps matching, I have 1 results.
if I have 3 timestamps matching, I have 2 results
... and so on...
So the newest timestamp in the table is always ignored by the query, WHY ?!
$timestamp_now = date('U');
$timestamp_10_day_back = $timestamp_now - 864000;
mysql_select_db("$db_visitors");
$sql = "SELECT DATE(FROM_UNIXTIME(visitors_timestamp))
FROM visitors
WHERE visitors_timestamp > $timestamp_10_day_back
ORDER BY visitors_timestamp DESC";
$sql = mysql_query($sql);
$row = mysql_fetch_array($sql);
while($row = mysql_fetch_array($sql)) {
echo $row[0] . "<br>";
}

Just remove
$row = mysql_fetch_array($sql);
...which is swallowing your first result

First row is being ignored because of the row $row = mysql_fetch_array($sql); then you call it again in your while loop . just remove this row .

try the code following
$n=count($row);
if($n>0){
for($i=0;$i<$n;$i++){
echo $row[i];}}
or
print_r($row);

Related

Adding a value to all elements in an array (php)

I have a query to get an array from a database.
$result = mysqli_query($con,"SELECT `Time_D` from `Schedule` where `Stop` = 1 ");
while ($row = mysqli_fetch_array($result) ) {
echo $row['Time_D'] . "<br>";
}
This array ($row) contains a lot of times, if I'm not mistaken.
I now want to add for example 10 minutes to all the elements in the array.
How do I do that?
Well, figured it out myself after all.
$result = mysqli_query($con,"SELECT `Time_D` from `Schedule` where `Stop` = 1 ");
//get database result
while ($row = mysqli_fetch_array($result) ) {
$rows[] = $row['Time_D']; //store all the times in one array
}
print_r ($rows);
echo "<br>";
$time_difference=600;
$i=0;
while (($i) < (count($rows)) ) {
$rows[$i] = ( strtotime($rows[$i]) ) + ($time_difference); //with timestamps, because, well, php and times...
$rows[$i] = date('H:i:s', ($rows[$i]) ); // back from timestamp to time
$i = $i +1;
}
print_r($rows);
You need to update like this
$row['Time_D'] = time() + 600;
or just 10 seconds
$row['Time_D'] += 600;
Then push it back to the database
mysql_query('update table_name set Time_D = '{$row['Time_D']}' where id = '{$row['id']}'
OR something to that end.
You can do it in SQL only:
"UPDATE `Schedule` SET `Time_D` VALUES = DATE_ADD(`Schedule`.`Time_D`,INTERVAL 10 MINUTE) where `Stop` = 1"
You might be mistaken. $row does not contain a lot of times. As long as there are still records available, $row is assigned the next row of the query result as an array. If you want to alter all the times, save them to a new array. In your while-loop (don't forget to declare $rows):
$rows[] = $row['Time_D'];
$rows now stores all the times. You can then (after the while-loop) iterate over $rows and alter the data.
$rows = array_map(function($time) {
return $time + (60 * 10); // Given $time is a timestamp
}, $rows);
If you don't want to save the times (i.e. directly output them in the while-loop), save the overhead of array_map and do it directly in the while-loop:
echo $row['Time_D'] + 60*10;
Depending on your exact situation you might want to use a key-value (i.e. id-to-time) storage for the times - otherwise you won't be able to refer them back to the "schedule" you are using.
If you only want to update the database records see Axel's answer.
You can do it from the mysql query itself by using DATE_ADD.
"SELECT DATE_ADD(`Time_D`,INTERVAL 10 MINUTE) AS 'Time_D' FROM `Schedule` WHERE `Stop` = 1 "
You can have a parameter like this in your php script:
$minutes_to_add = 10;
$result = mysqli_query($con,"SELECT DATE_ADD(`Time_D`,INTERVAL ".$minutes_to_add." MINUTE) AS 'Time_D' FROM `Schedule` WHERE `Stop` = 1 ");
while ($row = mysqli_fetch_array($result) )
{
echo $row['Time_D'] . "<br>";
}

Having trouble with MySQL double to date conversion

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.

Compare timestamp with date in php

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 .")";

Looping with mysql_fetch_array skipping over first row

I'm having trouble iterating through MySQL rows. This is my current code:
$query = "SELECT * FROM translations
WHERE iddoc = '$id'
AND submitted = 1;";
$result= mysqli_query($query);
$numrows = mysqli_num_rows($result);
$row2 = mysql_fetch_row($result);
if ($numrows > 0) {
while($eachrow = mysqli_fetch_array($result, MYSQLI_NUM)) {
echo $eachrow[0];
echo ", ";
echo $numrows;
}
}
The result of this is:
6, 2
But if there are 2 rows, why is the while loop ending after only 1 iteration? What am I understanding wrong?
EDIT: It appears to be displaying ONE LESS than the correct amount of rows. I.E. the while loop is running 1 less time than it should.
Found problem. I was fetching the first row with
$row2 = mysql_fetch_row($result);
outside of the while loop, thus causing it to start on the second row and skip over the first.

PHP - how to print each row of an array

I feel like I'm missing something really simple here. Here's my sql query:
$getpages = "SELECT id FROM pages WHERE account = 2 ORDER BY page_order";
$showpages = #mysqli_query ($dbc, $getpages);
$row = mysqli_fetch_array($showpages, MYSQLI_NUM);
I then print the first result:
echo $row[0];
And get a correct value, the id of the first page (by page order):
10
So I submit a form which simply turns that $row[0] into $row[1].
And nothing prints. I don't understand.
You have to do this:
while ($row = mysqli_fetch_array($showpages, MYSQLI_NUM)) {
$id = $row[id];
// do something with the id
echo $id . "<br/>"; // Echo every id
}
This will iterate through all of the results
mysqli_fetch_array is a special function as each time you call it, it outputs the NEXT row.
So:
while ($row = mysqli_fetch_array(stuff)){
$var = $row['sql column'];
// In your case "$var = $row[0];" to get the id for the first row found.
}
is how you use it.
This will keep running the function until mysqli_fetch_array() eventually returns false. These each time it will output a new row. And the $row array is the array of one row in the sql table.
Use :
print_r($row);
in the while loop to see exactly what's being returned for use.
$getpages = "SELECT id FROM pages WHERE account = 2 ORDER BY page_order";
$showpages = #mysqli_query ($dbc, $getpages);
$row = mysqli_fetch_array($showpages, MYSQLI_NUM);
Question how many rows are fetched in this query in this case id, So MYSQL will result to 1 row affected, But since you are using
$row = mysqli_fetch_array($showpages, MYSQLI_NUM);
This code you used will not output anything try
$row[n] as n-1
$result->fetch_assoc() or mysqli_fetch_assoc($result)
catch one line at a time, from a mysqli_result:
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
source: http://www.w3schools.com/php/php_mysql_select.asp

Categories