Search code examples
phpmysqlmaxsurvey

PHP MySQL max() function producing 5


I am working on a survey created by PHP and MySQL. So the issue is, I am trying to create a ResponseID, which is an ID specific for every person submitting the survey. So the code was created to add 1 to the existing max value from the ResponseID column. Here's the code:

//Response ID creation 
$query = "SELECT max(ResponseID) FROM survey";
$res = mysql_query($query);
$RID = $res+1; 

I know I can condense it, but here's the problem: I already entered one item on the table with the ResponseID of 1. When I tested the survey with different answers, the next ResponseID was 5. It should have been 2. So I tested again to see if it would produce 6 next time.

Unfortunately, it produced 5 again. I had my PHP guru looked it over and he said the coding was correct and it should be something from the database. I didn't set anything in the ResponseID except for it being an int. So why is it producing a 5? If anyone could please tell me how to go about fixing it, that would be super cool of you.

I am somewhat new to PHP.


Solution

  • $res will be a mysql statement handle, NOT the result of the query. you still have to actually FETCH a row from this $res result to access the value of the max() function in the query.

    This handle probably internally has identifier #5, which is why you're getting that "odd" result.

    The code should be:

    $sql = "SELECT MAX(responseID) AS max ...";
    $result = mysql_query($sql) or die(mysql_error());
    $row = mysql_fetch_assoc($result);
    
    $RID = $row['max'] + 1;