How to only select row if table timestamp has been updated - php

Currently im selecting most updated row using the following php block, i have an ajax loop which runs this php block every few seconds to return feed. i want to echo false to ajax when latest timestamp hasn't changed so that ajax doesn't duplicate results and fill my Div (#feed) with identical content.
<?php
require_once 'db_conx.php';
$Result = mysql_query("SELECT * FROM profiles ORDER BY lastupdated desc limit 1") or die (mysql_error());
while($row = mysql_fetch_array($Result)){
echo $row['name'];
}
mysql_close($con);
?>

Somewhere in the session, or in the requestor, you need to store the last fetched time. It would be better to store it as a session variable (this I presume is client-specific because different clients will have loaded at different times) and then fetch all records that have their lastupdated time greater than the last_fetched time.
Everytime entries are fetched from the DB, just update the last_fetched variable to the current timestamp.

If you are running this every 5 seconds, I would do something like
$Result = mysql_query("SELECT * FROM profiles WHERE lastupdated > ADDTIME( NOW( ) , '-00:00:05.00000' ) ORDER BY lastupdated desc limit 1") or die (mysql_error());
$num_rows = mysql_num_rows($result);
if ($num_rows = 0) {
return false;
} else {
return true;
}
This will give you any rows that have been updated in the last 5 seconds, if it is older than this it should have been picked up in the last run.
Hope this helps

When you retrieve your results from the server I'm guessing you store the timestamp of the last query in some PHP variable in order to compare the returned results of the next query.
I would concatenate the timestamp into your query as a where clause so your sql query would become something like
$Result = mysql_query("SELECT * FROM profiles WHERE lastupdated > " . $timestamp . " ORDER BY lastupdated desc limit 1") or die (mysql_error());
It's also worth noting that when this executes if there has been more than one profile updated since the last update cycle then it will only return the most recently updated row.
Does this answer your question?

Related

PHP get first row from SQL database

In a table I am developing, you can see that there is a person with the best known time. I would like to show it in my page, and so I used this code:
$con=mysqli_connect("localhost","user","pass","database");
if( $result2 = mysqli_query($con,"SELECT playername FROM 1_toad_circuit /*name of the table*/ LIMIT 0 , 30") ) {
$row = mysqli_fetch_row($result2);
printf ("%s \n", $row[0]);
}
As output I am not getting Itoi6 (person with the best time), but I have Catfish (the first in alphabetical order). I have 3 columns as you can see on the picture (link).
I say that I am pretty new with SQL and I would like to know what do I have to fix.
You need to add an ORDER BY clause to your statement and then order by whichever field you are storing the times in.
For example, if you had a "time" field:
SELECT playername, time FROM 1_toad_circuit
ORDER BY `time` ASC
LIMIT 1

PHP/MYSQL - Limit to last 500 then continue

I have a script that adds tweets to a data base and another one the fetches those tweets and displays via php/ajax. This all works good with an empty db but if I already have a lot of tweets in there It runs intp problems. What I'm trying to do now is set the msql query to get the first say 500 rows and then continue on as tweets are added and ignore the preivous 500 tweets etc. So start at the latest row, get the latest row upto 500max then next time its queried get ro 1001, 1002, 1003 each.
Any ideas on how I could do this? Once its got the latest 500 rows I could set a variable to change the query??
thanks
EDIT:
$ts = mysql_real_escape_string($_GET['lasttweet']);
$result = mysql_query("SELECT tweet_id, tweet_text, screen_name FROM tweets WHERE tweet_id > $ts LIMIT 100") or die (mysql_error());
Thsi is what I've tried for the query, but everytime it just gets another 100 old posts, where I need it to get new ones from then on.
If you don't want to update the records, use the full version of the LIMIT clause.
SELECT ... FROM tweets WHERE ... LIMIT 1 500
SELECT ... FROM tweets WHERE ... LIMIT 501 500
SELECT ... FROM tweets WHERE ... LIMIT 1001 500
of course, this will mean you need to keep track of which block you last retrieved.
you have to keep a different field like 'tweeted' with default value 0 and once you fetch the 500 records update tweeted field for those records to 1 and modify your select statement as
"SELECT tweet_id, tweet_text, screen_name FROM tweets WHERE tweeted != 1 LIMIT 500"
$ts = mysql_real_escape_string($_GET['lasttweet']);
mysql_query('SET CHARACTER SET utf8');
//Query to get number of rows
$numRows = mysql_query("SELECT tweet_id FROM tweets ") or die (mysql_error());
$rows = mysql_num_rows($numRows);
//Only show last/latest 500 tweets
$tweetLimit = 500;
if($_GET['lasttweet'] == 0){
if($rows > $tweetLimit){
$startFrom = $rows - $tweetLimit;
}
}else{
$startFrom = 0;
}
$result = mysql_query("SELECT tweet_id, tweet_text, screen_name, profile_image_url
FROM tweets
WHERE tweet_id > $ts
ORDER BY tweet_id
LIMIT $startFrom, $tweetLimit
")
or die (mysql_error());

extend mysql date

I am trying to code so that when a certain date is reached, then that is displayed in the report. What I would like to do is to find a way so that when a date is reached, ie, today, then keep the entry in the report until a user deletes it. So instead of it just showing today and not beyond, I need to find a way to show when a date is reached, it is displayed until deleted.
mysql_select_db($database_conn, $conn);
$query = "SELECT * FROM boxes WHERE customer = '$_SESSION[kt_idcode_usr]' AND destroy_date = DATE(NOW()) AND status = 1";
$result = mysql_query($query) or die(mysql_error());
SELECT * FROM boxes WHERE customer = '$_SESSION[kt_idcode_usr]' AND
destroy_date <= DATE(NOW()) AND status = 1";
this will return, when a date is reached, it is displayed until deleted.
if row is deleted no record would be there.

show 2 random rows instead of one

MY SQL QUERY:
$q = mysql_query("SELECT * FROM `ads` WHERE keywords LIKE '%$key%' ORDER BY RAND()");
RESULTS: KEYWORD123
This query searches and results in one random row but i want to show 2 random rows.
How to do that?
any solution?
how??
im grabbing it using this
$row = mysql_fetch_array($q); if ($row
<= 0){ echo 'Not found'; }else{ echo
$row['tab']; }
That query (as-is) will return more than one row (assuming more than one row is LIKE %$key%). If you're only seeing one record, it's possible you're not cycling through the result set, but rather pulling the top response off the stack in your PHP code.
To limit the response to 2 records, you would append LIMIT 2 onto the end of the query. Otherwise, you'll get every row that matches the LIKE operator.
//Build Our Query
$sql = sprintf("SELECT tab
FROM ads
WHERE keyword LIKE '%s'
ORDER BY RAND()
LIMIT 2", ('%'.$key.'%'));
// Load results of query up into a variable
$results = mysql_query($sql);
// Cycle through each returned record
while ( $row = mysql_fetch_array($result) ) {
// do something with $row
echo $row['tab'];
}
The while-loop will run once per returned row. Each time it runs, the $row array inside will represent the current record being accessed. The above example will echo the values stored in your tab field within your db-table.
Remove your order by and add a LIMIT 2
That happens after the execution of the SQL.
Right now you must be doing something like
$res = mysql_query($q);
$r = mysql_fetch_array($res);
echo $r['keywords'];
what you need to do
$q = mysql_query("SELECT * FROM ads WHERE keywords LIKE '%$key%' ORDER BY RAND() LIMIT 2");
$res = mysql_query($q);
while($r = mysql_fetch_array($res)){
echo "<br>" . $r['keywords'];
}
Hope that helps
This query will return all rows containing $key; if it returns only one now this is simply by accident.
You want to add a LIMIT clause to your query, cf http://dev.mysql.com/doc/refman/5.0/en/select.html
Btw both LIKE '%... and ORDER BY RAND() are performance killers

How do I fetch the last record in a MySQL database table using PHP?

I want to fetch the last result in MySQL database table using PHP. How would I go about doing this?
I have 2 Columns in the Table, MessageID(auto) & Message.
I already know how to connect to the database.
Use mysql_query:
<?php
$result = mysql_query('SELECT t.messageid, t.message
FROM TABLE t
ORDER BY t.messageid DESC
LIMIT 1') or die('Invalid query: ' . mysql_error());
//print values to screen
while ($row = mysql_fetch_assoc($result)) {
echo $row['messageid'];
echo $row['message'];
}
// Free the resources associated with the result set
// This is done automatically at the end of the script
mysql_free_result($result);
?>
The SQL query:
SELECT t.messageid, t.message
FROM TABLE t
ORDER BY t.messageid DESC
LIMIT 1
...uses the ORDER BY to set the values so the highest value is the first row in the resultset. The LIMIT says that of all those rows, only the first is actually returned in the resultset. Because messageid is auto-increment, the highest value is the most recent one...
Records in a relational database do not have an intrinsic "order" so you cannot fetch the "last" record without some kind of ORDER BY clause.
Therefore, in order to fetch the "last" record, simply reverse the ORDER BY clause (change ASC to DESC or vice versa) then select the first result.
If you have an auto-increment field and you just want to find the last value that was inserted, you can use the fact that the auto-increment fields are ever-increasing (therefore the "last" one will be the one with the highest value) and do something like this:
SELECT *
FROM my_table
ORDER BY id_field DESC
LIMIT 1
Of course you can select the last row by sorting DESC in your query. But what if you want to select the first row and then the last. You can run a new query, but you can also use the function mysql_data_seek. check code below:
$result = mysql_query('YOUR QUERY') or die('Invalid query: ' . mysql_error());
$row_first = mysql_fetch_array($result);
mysql_data_seek($result , (mysql_num_rows($result)-1));
$row_last = mysql_fetch_array($result);
Hope this helps
The MySql query would look like this:
select MessageID, Message
from Table
order by MessageID desc
limit 1;
I am too rusty with PHP to give you the right syntax for executing this.
This query works because you have an auto-incrementing identifying field (MessageID). By ordering the results by that field in descending (largest to smallest) order we are effectively returning the records in the table in reverse order. The limit 1 clause simply limits the result set to one record - the last one in the table.
What do you mean by "the last result"? You need to precise a bit more.
Do you mean "the last entry I registered"?
In this case you should use the appropriate method (depending on the extension you are using) mysqli->insert_id OR mysql_insert_id.
If you mean "the latest entry in the table", an SQL query such as Andrew Hare's is just what you need.
Do you mean the last record or do you need the id of the most recently inserted record? For that you would use the PHP mysql_insert_id() function. Or if you are using the myusqli extension use $mysqli->insert_id.
for some reason (which I don't know why), my boss force me to get the data in this way:
$message_arr = array();
while ($row = mysql_fetch_assoc($result)) {
$message_arr['messageid']= $row['messageid'];
$message_arr['message']= $row['message'];
}
return $message_arr;
Of course, you need everything from OMG Ponies's answer I'm just telling you another way to do it =)
I hope this help.
You should use SELECT query. How SELECT works.
SELECT * FROM table - selects everything in a table (id, row 1, row 2,...)
SELECT id FROM table - selects only particular row from table.
If you now know, how to select, you can use additional logic.
SELECT * FROM table ORDER by id DESC LIMIT 1;
selects everything from table table, orders it by id - orders it DESCENDING and limits the query to only one result.
If you would do it like this:
SELECT * FROM table ORDER by id ASC limit 1; - you would get 1 entry into database.
You can order it by any row you want.
Hope it helps.
One thing to remember is that data does not get saved in the insertion order in any MYSQL database. So in order to get the last entered record u will have to have an auto increment field. Since there is an auto increment field in this table we are good to go.
The below script will help to get the last entered record
<?php
$sql = "SELECT * FROM table_name ORDER BY MessageID DESC LIMIT 2";
$result_set = mysql_query($sql);
if($result_set){
while($row = mysql_fetch_array($result_set)) {
echo "Message Id: ".$row['MessageID']."<br>";
echo "Message: ".$row['Message']."<br>";
}
//creating alert
echo "<script type=\"text/javascript\">alert('Data was Retrieved
successfully');</script>";
}
else{
//creating alert
echo "<script type=\"text/javascript\">alert('ERROR! Could Not Retrieve
Data');</script>";
}
?>
The query selects all the records in the table and orders them according to the descending order of the MessageID (as it is the auto increment field) and limits the returned result to only one record. So since the table is ordered according to the descending order of the MessageID only the last entered record will be returned.
NOTE: if you are using a newer version you will have to use mysqli_query($connection_variable,$sql); instead of mysql_query($sql); and mysqli_fetch_array($result_set) instead of mysql_fetch_array($result_set)
$result = mysql_query('select max(id) from your_table ') or die('Invalid query: ' . mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo $row['id'];
echo $row['message'];
}
//
//
mysql_free_result($result);
simple like that
this code of php works fine
SELECT t.messageid, t.message
FROM TABLE t
ORDER BY t.messageid DESC
LIMIT 1
if you don't have concurrent entries going into some table.b'cause concurrent entries may not go in accordance of their insertion order.
$statement = $PDO->prepare("
SELECT MessageID,
Message
FROM myTable
ORDER BY MessageID DESC
LIMIT 1;
");
$statement->execute();
$result = $statement->fetch(\PDO::FETCH_ASSOC);
echo $result['MessageID']." and ".$result['Message'];

Categories