Abdel-Rahman Shoman Abdel-Rahman Shoman - 1 year ago 83
MySQL Question

Select MAX value in php SQL

So what I am trying to do is to select all columns from a certain table under two conditions

1- ID equals the value hold by my variable $user_id

SELECT * FROM table_name where r_id = $user_id

2- Column time is the max among the selection since the prvoius statement will return multiple records*

*Note the r_id is just a column name it is not the id

So now my query is as the following

$result = mysql_query("SELECT * FROM table_name where r_id = $user_id AND time = SELECT MAX(time) FROM table_name where r_id = $user_id ",$con) or die ('Error: '.mysql_error ());

However I am getting this error

Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT MAX(time) FROM table_name where r_id = 1' at line 1

I tried to search for the right syntax, however I did not find different syntax than mine

Any suggestion

Thanks in advance


Note that I don't have different tables, it is the same table.
That makes this problem different from the problems that looks similar online

So yes I did check on-line before asking and it does not seem that there is something similar to my problem

Answer Source
"SELECT * FROM table_name where r_id = $user_id AND time = (SELECT MAX(time) FROM table_name where r_id = $user_id) "
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download