EN
PHP - how to make MySQL update query with PDO?
4
points
In PHP it is possible to make SQL UPDATE
query with PDO in following way.
1. UPDATE
query with PDO example
<?php
if(isset($_GET['currentId'])
&& isset($_GET['newName']) && isset($_GET['newRole']))
{
$current_id = $_GET['currentId'];
$new_name = $_GET['newName'];
$new_role = $_GET['newRole'];
$db_name = 'test';
$db_host = '127.0.0.1'; // 'localhost'
$db_username = 'root';
$db_password = 'root';
$dsn = 'mysql:dbname=' . $db_name . ';host=' . $db_host . ';charset=utf8';
$pdo = new PDO($dsn, $db_username, $db_password);
$query = 'UPDATE `users` '
. 'SET `name` = :new_name, `role` = :new_role '
. 'WHERE `id` = :current_id';
$statement = $pdo->prepare($query);
if($statement === FALSE)
die('Query preparation error!');
$parameters = array(
'current_id' => $current_id,
'new_name' => $new_name,
'new_role' => $new_role
);
if($statement->execute($parameters))
{
$count = $statement->rowCount();
echo 'Number of updated rows is ' . $count . '.';
}
else
echo 'Query execution error!';
}
?>
Running:
http://localhost/update-user.php?currentId=3&newName=Matt&newRole=admin
Result:
Database:
2. Database preparation
create_tables.sql
file:
CREATE TABLE `users` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(100) NOT NULL,
`role` VARCHAR(15) NOT NULL,
PRIMARY KEY (`id`)
)
ENGINE=InnoDB;
insert_data.sql
file:
INSERT INTO `users`
(`name`, `role`)
VALUES
('John', 'admin'),
('Chris', 'moderator'),
('Kate', 'user'),
('Denis', 'moderator');