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
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.

 

 

Link to comment
Share on other sites

<?php

$dbQuery2="SELECT MAX(id) AS maxId FROM tutorials";
$result = mysql_query($dbQuery2,$db);
$numPosts = mysql_fetch_array($result);
$numPosts = $result['maxId'];

$numPosts = $numPosts + 1;

echo $numPosts;

?>

 

Try that?

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.