扫码一下
查看教程更方便
如果我们需要修改或更新 mysql 中的数据,我们可以使用 sql update 命令来操作。
以下是 update 命令修改 mysql 数据表数据的通用 sql 语法:
update table_name set field1=new-value1, field2=new-value2
[where clause]
当你需要更新数据表中指定行的数据时 where 子句是非常有用的。
以下我们将在 sql update 命令使用 where 子句来更新 jiyik_tbl 表中指定的数据:
以下示例将更新数据表中 jiyik_id 为 3 的 jiyik_title 字段值:
mysql> update jiyik_tbl set jiyik_title="学习 java" where jiyik_id=3;
query ok, 1 row affected (0.01 sec)
rows matched: 1 changed: 1 warnings: 0
mysql> select * from jiyik_tbl where jiyik_id=3;
---------- ------------- -------------- -----------------
| jiyik_id | jiyik_title | jiyik_author | submission_date |
---------- ------------- -------------- -----------------
| 3 | 学习 java | fql | 2007-05-06 |
---------- ------------- -------------- -----------------
1 row in set (0.00 sec)
从结果上看,jiyik_id 为 3 的 jiyik_title 已被修改。
php 中使用mysqli query()或mysql_query()函数来执行 sql 语句,你可以在 sql update 语句中使用或者不使用 where 子句。
注意:不使用 where 子句将数据表的全部数据进行更新,所以要慎重。
该函数与在 mysql> 命令提示符中执行 sql 语句的效果是一样的。
$mysqli->query($sql,$resultmode)
参数 | 描述 |
---|---|
$sql | 必需。规定要使用的 mysql 连接。 |
resultmode | 可选。一个常量。可以是下列值中的任意一个: mysqli_use_result(如果需要检索大量数据,请使用这个) mysqli_store_result(默认) |
以下示例将更新数据表中 jiyik_id 为 4 的 jiyik_title 字段值:
connect_errno ) {
printf("connect failed: %s\n", $mysqli->connect_error);
exit();
}
printf("connected successfully.\n");
if ($mysqli->query('update jiyiks_tbl set jiyik_title = "学习 python" where jiyik_id = 4')) {
printf("table jiyiks_tbl updated successfully.
");
}
if ($mysqli->errno) {
printf("could not update table: %s
", $mysqli->error);
}
$sql = "select jiyik_id, jiyik_title, jiyik_author, submission_date from jiyiks_tbl";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
printf("id: %s, title: %s, author: %s, date: %d \n",
$row["jiyik_id"],
$row["jiyik_title"],
$row["jiyik_author"],
$row["submission_date"]);
}
} else {
printf("no record found.\n");
}
mysqli_free_result($result);
$mysqli->close();
?>
执行结果如下:
table jiyik_tbl updated successfully.
id: 1, title: php 教程, author: 迹忆客, date: 2021
id: 2, title: mysql 教程, author: 春天花开, date: 2021
id: 3, title: 学习 java, author: fql, date: 2007
id: 4, title: 学习 python, author: 迹忆客, date: 2018