Home > Article > Backend Development > How to update data in a MySQL table using PHP?
To update data in a MySQL table, you can use MySQLi or PDO methods. MySQLi: Establish MySQLi connection Prepare SQL update query Execute update query PDO: Establish PDO connection Prepare SQL update query (use prepared statements) Bind parameters (if any) Execute update query
In PHP, updating data in a MySQL table involves using the MySQLi extension or PDO (PHP Data Objects). This article will introduce the steps for using these two methods and provide practical examples to illustrate.
$mysqli = new mysqli("localhost", "username", "password", "database_name");
$sql = "UPDATE table_name SET column_name = 'new_value' WHERE condition";
$mysqli->query($sql);
$dsn = "mysql:host=localhost;dbname=database_name"; $username = "username"; $password = "password"; $pdo = new PDO($dsn, $username, $password);
$statement = $pdo->prepare("UPDATE table_name SET column_name = :new_value WHERE condition");
$statement->bindParam(':new_value', $newValue);
$statement->execute();
Suppose we want to update the user table in the database and update the user name "old_username" to "new_username".
MySQLi Method:
$mysqli = new mysqli("localhost", "root", "password", "user_database"); $sql = "UPDATE users SET username = 'new_username' WHERE username = 'old_username'"; $mysqli->query($sql); $mysqli->close();
PDO Method:
$dsn = "mysql:host=localhost;dbname=user_database"; $username = "root"; $password = "password"; $pdo = new PDO($dsn, $username, $password); $statement = $pdo->prepare("UPDATE users SET username = :new_username WHERE username = :old_username"); $statement->bindParam(':new_username', 'new_username'); $statement->bindParam(':old_username', 'old_username'); $statement->execute();
The above is the detailed content of How to update data in a MySQL table using PHP?. For more information, please follow other related articles on the PHP Chinese website!