Page 1 of 1
Adding +1 to value from database
Posted: Mon Sep 14, 2009 10:08 am
by SL20
Hi all,
I am fairly new to PHP. I have written some code that adds 1 to the highest value in a database and stores it in a variable.
Code: Select all
$query = mysql_query("SELECT MAX(id) as maxnum FROM users");
$id = mysql_fetch_array($query);
$id = $id[maxnum]+1;
The code does work, but I am not sure if:
A) I have done this correctly, or if there is a better/easier way to do this?
B) Why I can't say: $id = $id[maxnum]++; ?
Re: Adding +1 to value from database
Posted: Mon Sep 14, 2009 10:44 am
by mattpointblank
What are you doing this for? If it's so you can 'guess' the ID of a row you just inserted, there's a function for this: mysql_insert_id (
http://us2.php.net/manual/en/function.m ... ert-id.php) - it gets the ID of the last row inserted by a query.
Re: Adding +1 to value from database
Posted: Mon Sep 14, 2009 10:52 am
by jazz090
Code: Select all
<?php
$query = mysql_query("SELECT MAX(id) FROM users AS max_id");
$max_id = mysql_fetch_assoc($query);
mysql_query("UPDATE users SET id = id+1 WHERE id = ".$max_id['max_id']);
?>
Re: Adding +1 to value from database
Posted: Mon Sep 14, 2009 11:48 am
by Ollie Saunders
You haven't retrieved the id with this:
You want:
Code: Select all
$id = mysql_fetch_object($query)->maxnum;
Re: Adding +1 to value from database
Posted: Mon Sep 14, 2009 4:27 pm
by Ollie Saunders
The value retrieved from the database is a string. The increment operator does not work on strings.
Code: Select all
php > $a = '1';
php > echo ++$a;
2
Also note:
Code: Select all
php > $a = 'a';
php > echo ++$a;
b
Re: Adding +1 to value from database
Posted: Mon Sep 14, 2009 5:20 pm
by Ollie Saunders
I hate being wrong, but, of course, I am.
I love being wrong these days; at least, about programming, I do. It means that just I learnt something.
Who/what said you can't?
The belief that $id was holding an id. It was actually holding an array and you can't increment that:
Code: Select all
php > $a = array(1);
php > var_dump($a);
array(1) {
[0]=>
int(1)
}
php > var_dump(++$a);
array(1) {
[0]=>
int(1)
}
Re: Adding +1 to value from database
Posted: Mon Sep 14, 2009 5:23 pm
by ricehigh
Also, you could do the math operation directly in you SQL statement:
Code: Select all
<?php
$query = mysql_query("SELECT MAX(id)+1 as maxnum FROM absence_db");
$id = mysql_fetch_object($query)->maxnum;
?>