「PHP+MySQL」PDOでデータを更新するサンプル

1. 1つのレコードで複数のフィールドを更新
phpコード:
$sql = “UPDATE students SET age = :age, hobby = :hobby WHERE stuid = :stuid";
$stmt = $con->prepare($sql);
$stuArr = array(':age’ => ’21’, ':hobby’ => 'game’, ':stuid’ => '1002’);
$stmt->execute($stuArr);

2.複数のフィールドとレコードを更新
phpコード:
$sql = “UPDATE students SET age = :age, hobby = :hobby WHERE stuid = :stuid";
$stmt = $conn->prepare($sql);
$stuArr = array(
array('age’=>’20’, 'hobby’=>swim, 'stuid’=>1003),
array('age’=>’21’, 'hobby’=>game, 'stuid’=>1002),
);

// foreachループ処理
foreach ($stuArr as $row) {
$stmt->execute(array(
':age’ => $row['age’],
':hobby’ => $row['hobby’],
':stuid’ => $row['stuid’])
);

MySQL

Posted by arkgame