PHP データベース(mysql)に入っているデータを更新
今回は、PHPを使い、データベース(mysql)に入っているデータを更新する方法を書きます。
基本的には、データを挿入する方法と同じです。
PHP データベース(mysql)にデータを挿入 - Three.jsを使って、作ってみた
このように書きます。
<?php //データベース接続 try { $dbh = new PDO('mysql:host=localhost;dbname=データベース名','ユーザー名','パスワード'); }catch(PDOException $e){ echo $e->getMessage(); exit(); } //更新する内容 $stmt = $dbh->prepare("update test set email = :email where id=2"); $stmt->execute(array(':email' => 'nya')); echo 'OK'; ?>
実行画面↓(上が実行前、下が実行後)
まず、こちらで、sql文を書きます。
$stmt = $dbh->prepare("update test set email = :email where id=2");
今回は、idが「2」のデータの「email」を更新するようにしています。
更新する内容を書いているところです。
$stmt->execute(array(':email' => 'nya'));
「:email」に 「nya」という文字を入れて、実行しています。