cturner Posted September 28, 2007 Share Posted September 28, 2007 I am trying to increment the mainid number and am having no luck with it. I already have an autoincrement primary key number so the mainid number is different to that. At the moment it add two entries to the database but doesn't add the incremented number. Can someone please help me with this? Thanks in advance. Here is my code: $query05 = mysql_query("SELECT mainid FROM menu") or die ("Could not query because: ".mysql_error()); $row05 = mysql_fetch_assoc($query05); $mainid = $row05['mainid']; if ($mainid < 0) { $insert06 = "INSERT INTO `menu` (`mainid`) VALUES ('$mainid + 1')"; f (mysql_query ($insert06)) { print "Mainid added."; } else { print "<p>Could not add the entry because: <b>" . mysql_error() . "</b>. The query was $insert06.</p>"; } } else { $insert07 = "INSERT INTO `menu` (`mainid`) VALUES ('0')"; if (mysql_query ($insert07)) { print "0"; } else { print "<p>Could not add the entry because: <b>" . mysql_error() . "</b>. The query was $insert07.</p>"; } } Quote Link to comment https://forums.phpfreaks.com/topic/70980-incrementing-a-number-then-inserting-it-into-the-database-problems/ Share on other sites More sharing options...
deadimp Posted September 28, 2007 Share Posted September 28, 2007 If you're just trying to increment the value of a field in a row, just use a simple update expression: update `menu` set `mainid`=`mainid`+1 where `id`=? where `id` is your primary index, and ? is the value of the id. If you want to insert an item into a table with one more than the largest value: insert into `menu` (`mainid`) values (max(`mainid`)+1) The max() statement ought to work. If not, you could use a subquery or sometihng like that. What's the point of this, though? You already have indexing with your auto increment field... Quote Link to comment https://forums.phpfreaks.com/topic/70980-incrementing-a-number-then-inserting-it-into-the-database-problems/#findComment-356918 Share on other sites More sharing options...
fenway Posted September 28, 2007 Share Posted September 28, 2007 Careful with those updates, they're not thread-safe... Quote Link to comment https://forums.phpfreaks.com/topic/70980-incrementing-a-number-then-inserting-it-into-the-database-problems/#findComment-356946 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.