Jump to content

Incrementing a number then inserting it into the database problems


Recommended Posts

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>";
}
}

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

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.