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
https://forums.phpfreaks.com/topic/97590-quicker-way-of-doing-this-mysql/
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

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.

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.