Everything PHP: SQL: UPDATE

Published on Jul 29, 2009   //  Development
Off

Everything PHP

An update query will allow you to update an existing row (or rows) in the database based on a certain set of criteria. In an update query, you specify the fields and their new values and some criteria on which rows to update.

[sql]UPDATE table SET field = ‘value’[/sql]

You may choose to not specify which rows to update, if you want all the rows in the table to be updated.

[sql]UPDATE table SET field1 = ‘value1′, field2 = ‘value2′ WHERE field3 = ‘value3′[/sql]

Using the where clause will allow you to set the criteria for updating the rows.

It is also possible to limit the number of tables that will be updated. By using a limit parameter you can limit the number of rows that will be matched with the where clause (MySQL won’t update the row if the fields are already on the field, but it will still count this row against the limit).

[sql]UPDATE table SET field1 = ‘value1′, field2 = ‘value2′ WHERE field3 = ‘value3′ OR field4 = ‘value3′ LIMIT 4[/sql]

You may also specify multiple tables to be updated in a single query. Which looks like this:

[sql]UPDATE table1, table2 table1.field1 = ‘value1′, table2.field1 = ‘value2′ WHERE table1.field3 = ‘value3′ OR table2.field3 = ‘value5′[/sql]

There you have it, an update query.