MySQL UPDATE查询用于更新MySQL数据库中表中的现有记录。它可以用于同时更新一个或多个字段。并且可用于使用WHERE子句指定任何条件。(相关推荐:《MySQL教程》)
UPDATE更新查询的基本语法是
Where Update
查询的实现:
让我们考虑下表“Data”,其中包含四列“ID”,“FirstName”,“LastName”和“Age”。
要更新“Data”表中“ID”为201的人员的“Age”,我们可以使用以下代码:
使用过程方法更新查询:
<?php $link = mysqli_connect("localhost", "root", "", "Mydb"); if($link === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } $sql = "UPDATE data SET Age='28' WHERE id=201"; if(mysqli_query($link, $sql)){ echo "Record was updated successfully."; } else { echo "ERROR: Could not able to execute $sql. " . mysqli_error($link); } mysqli_close($link); ?>
输出:更新后的表格
Web浏览器上的输出:
使用面向对象的方法更新查询:
<?php $mysqli = new mysqli("localhost", "root", "", "Mydb"); if($mysqli === false){ die("ERROR: Could not connect. " . $mysqli->connect_error); } $sql = "UPDATE data SET Age='28' WHERE id=201"; if($mysqli->query($sql) === true){ echo "Records was updated successfully."; } else{ echo "ERROR: Could not able to execute $sql. " . $mysqli->error; } $mysqli->close(); ?>
使用PDO方法更新查询:
<?php try{ $pdo = new PDO("mysql:host=localhost; dbname=Mydb", "root", ""); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e){ die("ERROR: Could not connect. " . $e->getMessage()); } try{ $sql = "UPDATE data SET Age='28' WHERE id=201"; $pdo->exec($sql); echo "Records was updated successfully."; } catch(PDOException $e){ die("ERROR: Could not able to execute $sql. " . $e->getMessage()); } unset($pdo); ?>
本篇文章就是关于MySQL更新查询的介绍,希望对需要的朋友有所帮助!
以上是MySQL如何实现更新查询?的详细内容。更多信息请关注PHP中文网其他相关文章!