Garg Garg - 1 month ago 5
PHP Question

Result always go in same condition

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


enter image description here

UPDATE2:

echo (time() - strtotime($row['update_time']))
-> 54143

echo strtotime($row['update_time'])
-> 1477552149

Answer

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';
}
Comments