Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Update multiple MySQL fields in single query

I am basically just trying to update multiple values in my table. What would be the best way to go about this? Here is the current code:

$postsPerPage = $_POST['postsPerPage'];
$style = $_POST['style'];

mysql_connect ("localhost", "user", "pass") or die ('Error: ' . mysql_error());
mysql_select_db ("db");

mysql_query("UPDATE settings SET postsPerPage = $postsPerPage WHERE id = '1'") or die(mysql_error());

The other update I want to include is:

mysql_query("UPDATE settings SET style = $style WHERE id = '1'") or die(mysql_error());

Thanks!

like image 558
Chris Avatar asked Mar 10 '11 00:03

Chris


People also ask

How do I UPDATE multiple columns in MySQL?

MySQL UPDATE command can be used to update multiple columns by specifying a comma separated list of column_name = new_value. Where column_name is the name of the column to be updated and new_value is the new value with which the column will be updated.

How do I UPDATE all values in a column in MySQL?

To set all values in a single column MySQL query, you can use UPDATE command. The syntax is as follows. update yourTableName set yourColumnName =yourValue; To understand the above syntax, let us create a table.

How do you UPDATE multiple values in one column in SQL?

First, specify the table name that you want to change data in the UPDATE clause. Second, assign a new value for the column that you want to update. In case you want to update data in multiple columns, each column = value pair is separated by a comma (,). Third, specify which rows you want to update in the WHERE clause.

Can we set multiple values in UPDATE query?

The UPDATE statement is capable of updating more than one row.


1 Answers

Add your multiple columns with comma separations:

UPDATE settings SET postsPerPage = $postsPerPage, style= $style WHERE id = '1'

However, you're not sanitizing your inputs?? This would mean any random hacker could destroy your database. See this question: What's the best method for sanitizing user input with PHP?

Also, is style a number or a string? I'm assuming a string, so it would need to be quoted.

like image 178
Fosco Avatar answered Oct 07 '22 19:10

Fosco