如果我們需要修改或更新 MySQL 中的數(shù)據(jù),我們可以使用 SQL UPDATE 命令來操作。
以下是 UPDATE 命令修改 MySQL 數(shù)據(jù)表數(shù)據(jù)的通用 SQL 語法:
UPDATE table_name SET field1=new-value1, field2=new-value2 [WHERE Clause]
你可以同時(shí)更新一個(gè)或多個(gè)字段。
你可以在 WHERE 子句中指定任何條件。
你可以在一個(gè)單獨(dú)表中同時(shí)更新數(shù)據(jù)。
當(dāng)你需要更新數(shù)據(jù)表中指定行的數(shù)據(jù)時(shí) WHERE 子句是非常有用的。
通過命令提示符更新數(shù)據(jù)
以下我們將在 SQL UPDATE 命令使用 WHERE 子句來更新 nhooo_tbl 表中指定的數(shù)據(jù):
以下示例將更新數(shù)據(jù)表中 nhooo_id 為 3 的 nhooo_title 字段值:
mysql> UPDATE nhooo_tbl SET nhooo_title='學(xué)習(xí) C++' WHERE nhooo_id=3; Query OK, 1 rows affected (0.01 sec) mysql> SELECT * from nhooo_tbl WHERE nhooo_id=3; +-----------+--------------+---------------+-----------------+ | nhooo_id | nhooo_title | nhooo_author | submission_date | +-----------+--------------+---------------+-----------------+ | 3 | 學(xué)習(xí) C++ | CAINIAOPLUS.COM | 2016-05-06 | +-----------+--------------+---------------+-----------------+ 1 rows in set (0.01 sec)
從結(jié)果上看,nhooo_id 為 3 的 nhooo_title 已被修改。
PHP 中使用函數(shù) mysqli_query() 來執(zhí)行 SQL 語句,你可以在 SQL UPDATE 語句中使用或者不使用 WHERE 子句。
注意:不使用 WHERE 子句將數(shù)據(jù)表的全部數(shù)據(jù)進(jìn)行更新,所以要慎重。
該函數(shù)與在 mysql> 命令提示符中執(zhí)行 SQL 語句的效果是一樣的。
以下示例將更新 nhooo_id 為 3 的 nhooo_title 字段的數(shù)據(jù)。
<?php $dbhost = 'localhost'; // mysql服務(wù)器主機(jī)地址 $dbuser = 'root'; // mysql用戶名 $dbpass = '123456'; // mysql用戶名密碼 $conn = mysqli_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('連接失敗: ' . mysqli_error($conn)); } // 設(shè)置編碼,防止中文亂碼 mysqli_query($conn , "set names utf8"); $sql = 'UPDATE nhooo_tbl SET nhooo_title="學(xué)習(xí) Python" WHERE nhooo_id=3'; mysqli_select_db( $conn, 'NHOOO' ); $retval = mysqli_query( $conn, $sql ); if(! $retval ) { die('無法更新數(shù)據(jù): ' . mysqli_error($conn)); } echo '數(shù)據(jù)更新成功!'; mysqli_close($conn); ?>