PHP UPDATE
The "UPDATE" statement is used to modify existing records in a database table. In PHP, we can use the built-in function mysqli_query()
to execute the UPDATE query. The syntax for the UPDATE query in PHP is as follows:
Syntax
mysqli_query($connection, "UPDATE table_name SET column1 = 'value1', column2 = 'value2' WHERE condition");
Here,
$connection
is the MySQL database connection object.table_name
is the name of the table whose records need to be updated.column1
,column2
are the columns to be updated.value1
,value2
are the new values to be set in the columns.condition
is the WHERE clause to specify which records need to be updated.
Example
Let's consider an example to understand how to use UPDATE in PHP. Suppose we have a table "users" with columns "name", "email", "phone", and we want to update the phone number of a particular user whose name is "John". The following code will update the record for John in the users table:
$connection = mysqli_connect("localhost", "username", "password", "database");
mysqli_query($connection, "UPDATE users SET phone = '1234567890' WHERE name = 'John'");
Output
The mysqli_query()
function returns TRUE
on success and FALSE
on failure. In case of an error, we can use the mysqli_error()
function to get the error message.
Explanation
In the above example, we first establish a database connection using mysqli_connect()
function. Then, we execute the UPDATE query using mysqli_query()
function. The query updates the phone number of the user with name "John" in the users table. The WHERE clause specifies that only the record with name "John" will be updated.
Use
The UPDATE statement in PHP is used to modify existing records in a database table. It is commonly used in web applications where the user needs to update their information, such as their name, address, phone number, etc. It is also used to update the state of a record, such as setting a record as "completed" or "cancelled".
Important Points
- Make sure to use single quotes for string values in the SET clause.
- Always use the WHERE clause to specify which records to update. Omitting the WHERE clause will update all the records in the table, which can have undesirable consequences.
- Remember to sanitize user input to prevent SQL injection attacks.
Summary
- The PHP UPDATE statement is used to modify existing records in a database table.
- The syntax for UPDATE is:
mysqli_query($connection, "UPDATE table_name SET column1 = 'value1', column2 = 'value2' WHERE condition")
, - Use single quotes for string values in the SET clause and the WHERE clause to specify the records to update.
- Sanitize input to prevent SQL injection attacks.