Summarize some knowledge points of vue3: MySQL UPDATE update

MySQL UPDATE update

If we need to modify or update data in MySQL, we can use the SQL UPDATE command to operate.

grammar

The following is the general SQL syntax for the UPDATE command to modify the data in the MySQL data table:


UPDATE table_name SET field1=new-value1, field2=new-value2
[WHERE Clause]
  • You can update one or more fields at the same time.
  • You can specify any conditions in the WHERE clause.
  • You can update data concurrently in a single table.

The WHERE clause is very useful when you need to update the data of a specific row in the data table.


Update data via command prompt

Below we will use the WHERE clause in the SQL UPDATE command to update the specified data in the kxdang_tbl table:

example

The following example will update the value of the kxdang_title field with kxdang_id 3 in the data table:

SQL UPDATE statement:

mysql> UPDATE kxdang_tbl SET kxdang_title='学习 C++' WHERE kxdang_id=3;
Query OK, 1 rows affected (0.01 sec)
 
mysql> SELECT * from kxdang_tbl WHERE kxdang_id=3;
+-----------+--------------+---------------+-----------------+
| kxdang_id | kxdang_title | kxdang_author | submission_date |
+-----------+--------------+---------------+-----------------+
| 3         | 学习 C++   | RUNOOB.COM    | 2016-05-06      |
+-----------+--------------+---------------+-----------------+
1 rows in set (0.01 sec)

From the results, the kxdang_title with kxdang_id 3 has been modified.


Update data using PHP script

PHP uses the function mysqli_query() to execute SQL statements, and you can use or not use the WHERE clause in the SQL UPDATE statement.

**Note:** Do not use the WHERE clause to update all the data in the data table, so be careful.

This function has the same effect as executing SQL statements in the mysql> command prompt.

example

The following example will update the data of kxdang_title field whose kxdang_id is 3.

MySQL UPDATE statement test:

<?php
$dbhost = 'localhost';  // mysql服务器主机地址
$dbuser = 'root';            // mysql用户名
$dbpass = '123456';          // mysql用户名密码
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
    die('连接失败: ' . mysqli_error($conn));
}
// 设置编码,防止中文乱码
mysqli_query($conn , "set names utf8");
 
$sql = 'UPDATE kxdang_tbl
        SET kxdang_title="学习 Python"
        WHERE kxdang_id=3';
 
mysqli_select_db( $conn, 'RUNOOB' );
$retval = mysqli_query( $conn, $sql );
if(! $retval )
{
    die('无法更新数据: ' . mysqli_error($conn));
}
echo '数据更新成功!';
mysqli_close($conn);
?>

Guess you like

Origin blog.csdn.net/m0_74760716/article/details/131460645