Alejandro Suarez
Alejandro Suarez

Reputation: 168

MYSQL-PHP Get value of a specific cell(field) and use it in PHP IF statement

im hoping anyone can help with this issue. Heads up im in the process of learning both PHP and MySQL so please bear with me. I have the following table:

ID  whid    securitybatch   radionumber userbatch    status       dateofentry
1   AAA        123456           1        5555555    Available   11/10/2016 9:20
2   BBB        123456           7        1234567    Available   11/10/2016 16:50
3   BBB        123456           6        6666666    Deployed    11/11/2016 7:43
4   XXX        123456           3        2222222    Deployed    11/11/2016 19:52
5   XXX        123456           4        1234567    Deployed    11/11/2016 20:03
6   AAA        123456           6        1111116    Deployed    11/11/2016 21:43
7   XXX        123456           2        2222222    Deployed    11/11/2016 21:52

Im trying the get the highlighted value and use it in an IF statement, the issue is my specific requirements.

The user 1234567 has two entries on the table and eventually a lot more, i want to get the value of the status column of the latest dated entry for that user, being the one that is selected, if that makes sense...ive been trying and researching but its beating me up...

$query = "SELECT status FROM radiodata WHERE userbatch='$user' AND    MAX(dateofentry)";
$result = mysqli_query($dbc, $query);     

So i would love to get the value 'Deployed' a string i suppose and use it as follows:

if($result === 'Deployed') {
    echo 'Not returned';
} else {
    echo 'Returned';
}

Thanks in advance, any ideas/solutions are welcome.

Cheers

Upvotes: 3

Views: 107

Answers (3)

Chandana Kumara
Chandana Kumara

Reputation: 2645

You can do as follows:

$query = "SELECT status FROM radiodata WHERE userbatch='$user' ORDER BY 
          dateofentry  DESC LIMIT 1";
$result = mysqli_query($dbc, $query); 

$row = mysqli_fetch_row($result);  

if($row[0] == 'Deployed') {
    echo 'Not returned';
} else {
    echo 'Returned';
}

Upvotes: 1

e4c5
e4c5

Reputation: 53734

That query in it's current form is invalid and will lead to a syntax error.

$query = "SELECT status FROM radiodata WHERE userbatch='$user' ORDER BY dateofentry DESC LIMIT 1";
$result = mysqli_query($dbc, $query);     

You really shouldn't be using string concatenation like this, but let's leave that aside for now. This query will now return you a single row result.

Having done that you still can't compare it to deployed in that manner

$row = mysqli_fetch_array($result);
if ($row['status'] == 'Deployed') {

}

Upvotes: 1

T..
T..

Reputation: 91

You can order the query by your dateofentry

just add

ORDER BY dateofentry DESC LIMIT 1

to the end of your query and it'll sort it by that column and then the LIMIT will only get you the one result

Upvotes: 1

Related Questions