Home  >  Article  >  Backend Development  >  How to update data in a MySQL table using PHP?

How to update data in a MySQL table using PHP?

PHPz
PHPzOriginal
2024-06-04 16:43:011109browse

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

如何使用 PHP 更新 MySQL 表中的数据?

How to update data in a MySQL table using PHP

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.

Use MySQLi to update data

  1. Establish MySQLi connection:
$mysqli = new mysqli("localhost", "username", "password", "database_name");
  1. Prepare SQL update query:
$sql = "UPDATE table_name SET column_name = 'new_value' WHERE condition";
  1. Execute update query:
$mysqli->query($sql);

Use PDO to update data

  1. Establish PDO connection:
$dsn = "mysql:host=localhost;dbname=database_name";
$username = "username";
$password = "password";

$pdo = new PDO($dsn, $username, $password);
  1. Prepare SQL Update query:
$statement = $pdo->prepare("UPDATE table_name SET column_name = :new_value WHERE condition");
  1. Bind parameters (if required):
$statement->bindParam(':new_value', $newValue);
  1. Execute update query:
$statement->execute();

Practical Case

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn