 |
|
|
| View previous topic :: View next topic |
| Author |
Message |
lizciz
Joined: 19 Mar 2008 Posts: 10
|
Posted: Fri Mar 21, 2008 2:43 pm Post subject: DB_Table increase single integer value by one (1) |
|
|
If I were to manually write a SQL query to increase a integer value by one, it would look something like this
"UPDATE table SET field = field+1 WHERE id = '$id'"
Can this be done using the DB_Table function update()? I tried this:
| Code: |
$update = array(
'field' => 'field+1'
);
$where = "id = '$id'";
$db->update('table', $update, $where);
|
Which didn't work, since the validation expect an integer value, not a string like 'field+1'. The only solution I could come up with was to first execute a select() to retrieve the field value, increasing it by one, and then using that value in the update array.
Is there a better way? |
|
| Back to top |
|
 |
mark

Joined: 07 Jan 2007 Posts: 1011
|
Posted: Fri Mar 21, 2008 6:45 pm Post subject: |
|
|
That's not possible with update(). The default validation could be disabled, and the string value would be accepted then, but the value would still be quoted, and then either rejected by the DBMS or converted to maybe 0.
The easiest way would be to use the query() method of DB:
| Code: |
$db_object->query('UPDATE table SET field = field + 1 WHERE id = ?', $id);
|
(With MDB2 there are similar methods.) |
|
| Back to top |
|
 |
lizciz
Joined: 19 Mar 2008 Posts: 10
|
Posted: Fri Mar 21, 2008 10:09 pm Post subject: |
|
|
Thanks alot for your awnser! I got it working.
Although I acctually never tried the the query() function, because I read in the documentation that it is supposed to be used for select statements only. Instead I used exec() which seems to work splendid, as in
| Code: |
$sql = "UPDATE ...";
$update = $db->getDBInstace()->exec($sql);
// (where getDBInstance() returns a reference to a MDB2 object)
if (PEAR::IsError($update)) {
// ...
}
|
|
|
| Back to top |
|
 |
mark

Joined: 07 Jan 2007 Posts: 1011
|
Posted: Sat Mar 22, 2008 12:11 am Post subject: |
|
|
| lizciz wrote: | | Although I acctually never tried the the query() function, because I read in the documentation that it is supposed to be used for select statements only. Instead I used exec() which seems to work splendid, as in [...] |
Well, yes, right, as written, my example was for the DB package where query() is a good choice. With MDB2, exec() is right. |
|
| Back to top |
|
 |
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
|