0

I have the following code which echo the max id from my table challenge but its giving me this error :

Warning: mysql_result(): id not found in MySQL result index 6 in D:\xampp\htdocs\challenge.php on line 8

Here's my code:

<?php

    require('config.php');


        $result = mysql_query("SELECT max(id) FROM `challenge`");
        $id = mysql_result($result, 0, 'id');
        echo $id;
    ?>

My table challenge does have an id column then why PHP is not able to find. I do have a correct connection to my database.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Ashesh Kumar
  • 223
  • 2
  • 12
  • 2
    Please, [don't use `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php), They are no longer maintained and are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). Learn about [prepared statements](http://en.wikipedia.org/wiki/Prepared_statement) instead, and use [PDO](http://us1.php.net/pdo) or [MySQLi](http://us1.php.net/mysqli). [This article](http://php.net/manual/en/mysqlinfo.api.choosing.php) will help you decide. – Jay Blanchard Oct 14 '14 at 17:25

2 Answers2

5

Like it says, you're not returning a column called "id", you're returning one called "max(id)". If you want to refer to the column as "id" use an alias:

$result = mysql_query("SELECT max(id) AS id FROM `challenge`");

Note the AS id

(Sidenote: as Jay Blanchard says in his comment, mysql_* functions are deprecated over security concerns. Look into MySQLi and, as part of it, prepared statements, instead.)

Mitya
  • 33,629
  • 9
  • 60
  • 107
0

when using aggregate functions like Max, Min try to give an Alias then you can access it in result.

$result = mysql_query("SELECT max(id) as id FROM `challenge`");

but this function is slower than mysql_fetch_row(), mysql_fetch_array(), mysql_fetch_assoc() and mysql_fetch_object()

and secondly you should not use mysql_* functions instead use mysqli or PDO

Maz I
  • 3,664
  • 2
  • 23
  • 38