In PHP, database records can be inserted, updated and deleted through INSERT, UPDATE and DELETE statements respectively. When inserting data, use an INSERT statement to specify the target table and columns and provide the inserted values. When updating data, use the UPDATE statement to specify the target table and columns, and specify update conditions in the WHERE clause. When deleting data, use the DELETE statement to specify the target table and specify the deletion conditions in the WHERE clause. For specific code examples and practical cases, please refer to the article.
How to insert, update and delete database records in PHP
Insert data
Code
$sql = "INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...)";
Syntax
INSERT INTO
: Indicates the table into which data is to be inserted. (column1, column2, ...)
: The column into which data is to be inserted. VALUES (value1, value2, ...)
: The value to be inserted. Update data
Code
$sql = "UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition";
Syntax
UPDATE
: Indicates the table whose data is to be updated. SET column1 = value1, column2 = value2, ...
: The columns to be updated and their new values. WHERE condition
: Specify the condition of the row to be updated. Delete data
Code
$sql = "DELETE FROM table_name WHERE condition";
Syntax
DELETE FROM
: Indicates the table from which data is to be deleted. WHERE condition
: Specify the condition of the rows to be deleted. Practical case
Suppose there is a table named customers
, with id
, Name
and email
are three columns.
Insert record
$stmt = $conn->prepare("INSERT INTO customers (name, email) VALUES (?, ?)"); $stmt->bind_param("ss", $name, $email); $name = "John Doe"; $email = "johndoe@example.com"; $stmt->execute();
Update record
$stmt = $conn->prepare("UPDATE customers SET email = ? WHERE id = ?"); $stmt->bind_param("si", $email, $id); $email = "johndoe123@example.com"; $id = 1; $stmt->execute();
Delete record
$stmt = $conn->prepare("DELETE FROM customers WHERE id = ?"); $stmt->bind_param("i", $id); $id = 1; $stmt->execute();
The above is the detailed content of How to insert, update and delete database records in PHP?. For more information, please follow other related articles on the PHP Chinese website!