Reputation: 3375
I have one simple script which I want to check if database isn't updated last 3 hours to use IF
block if is updated to use ELSE
. What I found is that it is always use IF
condition and never go in else block.
public static function getPrice() {
$servername = "localhost";
$username = "myUsername";
$password = "myPassword";
$dbname = "myDbName";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query = "select update_time from price";
$result = mysqli_query($conn, $query);
while($row = $result->fetch_assoc())
{
if (time() - strtotime($row['update_time']) > 3 * 3600)
{
$urldata = get_curl_content('https://example.com/api');
$rates = json_decode($urldata, TRUE);
$price = @$rates['USD'];
echo 'a';
}
else {
$price = $row['price'];
echo 'b';
}
}
return $price;
}
No matter how what is in $row['update_time']
it is always showing what is it in IF
... i.e. from the url not from database.
What I miss here?
UPDATE: in phpmyadmin
SELECT update_time FROM `price`
Showing rows 0 - 0 (1 total)
0-0
but I see the result.. it's a table without primary key etc. Just two columns price
and update_time
UPDATE2:
echo (time() - strtotime($row['update_time']))
-> 54143
echo strtotime($row['update_time'])
-> 1477552149
Upvotes: 0
Views: 68
Reputation: 3375
You can change the query like this
$query = "SELECT * FROM price WHERE update_time < (NOW() - INTERVAL 3 HOUR)";
Then based on this query
// your connection
$query = "SELECT * FROM price WHERE update_time < (NOW() - INTERVAL 3 HOUR)";
$result = mysqli_query($conn, $query);
if($res->num_rows > 0) {
echo 'not updated';
} else {
echo 'updated';
}
Upvotes: 0
Reputation: 33813
public static function getPrice() {
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
$conn = new mysqli( $servername, $username, $password, $dbname );
if ( $conn->connect_error ) {
die("Connection failed: " . $conn->connect_error);
}
$query = "select `price`, `update_time` from `price`";
$result = $conn->query( $query );
$max = abs( 3 * 3600 );
$price=false;
if( $result ){
while( $row = $result->fetch_assoc() ) {
try{
if ( abs( time() - strtotime( $row['update_time'] ) ) > $max ) {
$urldata = get_curl_content( 'https://example.com/api' );
if( $urldata ){
$rates = json_decode( $urldata, TRUE );
$price = is_array( $rates ) && array_key_exists( 'USD', $rates ) ? $rates['USD'] : 'error';
echo 'a';
} else {
echo 'error fetching from api';
}
} else {
$price = $row['price'];
echo 'b';
}
}catch( Exception $e ){
echo $e->getMessage();
}
}
}
return $price;
}
Upvotes: 2