Jump to content

[SOLVED] SELECT MAX(id) not working!


Urbley

Recommended Posts

Ok I have a table with a bunch of tutorials.  id is a field that holds a unique id.  Very simple!  I started off using a count to get the next id, i.e. count all the tutorials in the table and then, nextId = count + 1 kind of thing.

 

This was fine until I discovered some tutorials may need to be deleted so if i deleted number 2 and then tried to add one, it would have the same id as the one before this one was entered.  i.e. 2 tutorials with the an id of 6 like is happening at the minute.

 

I want to use the SELECT MAX statement but it's not working for me.  Here's what I have so far.

 

$dbQuery2="SELECT MAX(id) AS maxId FROM tutorials";
$numPosts = mysql_query($dbQuery2,$db);

$numPosts = $numPosts + 1;

echo $numPosts;

 

$db is my connection info.  All connection info is fine.  The echo is echoing NOTHING! =S

 

Any ideas people?

 

Thanks,

 

Steve.

Link to comment
https://forums.phpfreaks.com/topic/51172-solved-select-maxid-not-working/
Share on other sites

Sorry that was a typo on my behalf when putting it on here.  Edited it.  That query is now returning a value of 4 every single time.  I can tell you that there are 6 entries in my database at the mo with id's of 2, 3, 5, 6, 7 and 8.  When I try to add a new entry it gives an id of 4! Where it should be 9.

 

 

try something like this

<?php
$dbQuery2="SELECT MAX(id) AS maxId FROM tutorials"; //create the query

$result = mysql_query($dbQuery2,$db); //execute the query, returns a resource id not what you want yet

$row = mysql_fetch_assoc($result); //turns the resource id into a associative array of data

$numposts = $row['maxId']; //returns what you want

$numPosts = $numPosts + 1; //increments it by 1

echo $numPosts; //prints it out to the page
?>

 

EDIT: chigley you beat me to it

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.