Jump to content

Incrementing a number then inserting it into the database problems


cturner

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

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.