Jump to content

Quicker way of doing this (MySQL)?


LemonInflux

Recommended Posts

<?php

$query = mysql_query("SELECT * FROM `table` WHERE `id` = '1'") or die(mysql_error());

while($row = mysql_fetch_assoc)
{
$sql = mysql_query("UPDATE `table` SET `field` = '". $row['field'] + 1 ."' WHERE `id` = '1'");
}

?>

 

There are probably a hundred mistakes, but this is an example. I'm trying to add 1 to a field's value, but the only way I can think how to do it is to start a loop and then use $row['field'] + 1. Surely there's a quicker way? (For example, $v + 1 is the same as $v++ in PHP)

Link to comment
Share on other sites

UPDATE table SET field = table.field+1 WHERE id=table.id

 

 

someone will need to check this because its just a guess, however it should work for you.

 

gdlk

 

That will update all rows (id always equals id)

<?php
$id = 1;
mysql_query ("UPDATE table SET field = field+1 WHERE id = $id");

 

MySQL, MSSQL compatible. I don't use postgres but should be OK.

 

You will probably only have difficulty across dbms when you try using SQL functions, especially datetime ones. Date formats can also be a problem with different dbms

Link to comment
Share on other sites

that will set field to the string value "field+1". Use

UPDATE `table` SET `field` = `field`+ 1 WHERE `id` = '$id'

 

But now it is no longer compatible with MSSQL. The equivalent MSSQL (to allow spaces/resrved words in column names) is

 

UPDATE [table] SET [field] = [field] + 1 WHERE [id] = $id

 

(Note MySQL allows '$id' even if $id is numeric; other dbms do not.

Link to comment
Share on other sites

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.