
- MariaDB 教程
- MariaDB - 首頁
- MariaDB - 簡介
- MariaDB - 安裝
- MariaDB - 管理
- MariaDB - PHP 語法
- MariaDB - 連線
- MariaDB - 建立資料庫
- MariaDB - 刪除資料庫
- MariaDB - 選擇資料庫
- MariaDB - 資料型別
- MariaDB - 建立表
- MariaDB - 刪除表
- MariaDB - 插入查詢
- MariaDB - 選擇查詢
- MariaDB - Where 子句
- MariaDB - 更新查詢
- MariaDB - 刪除查詢
- MariaDB - Like 子句
- MariaDB - Order By 子句
- MariaDB - 連線
- MariaDB - 空值
- MariaDB - 正則表示式
- MariaDB - 事務
- MariaDB - Alter 命令
- 索引和統計表
- MariaDB - 臨時表
- MariaDB - 表克隆
- MariaDB - 序列
- MariaDB - 管理重複資料
- MariaDB - SQL 注入防護
- MariaDB - 備份方法
- MariaDB - 備份載入方法
- MariaDB - 有用函式
- MariaDB 有用資源
- MariaDB - 快速指南
- MariaDB - 有用資源
- MariaDB - 討論
MariaDB - 插入查詢
在本章中,我們將學習如何在表中插入資料。
將資料插入表需要使用 INSERT 命令。該命令的通用語法是在 INSERT 後跟表名、欄位和值。
檢視下面給出的通用語法:
INSERT INTO tablename (field,field2,...) VALUES (value, value2,...);
該語句需要對字串值使用單引號或雙引號。該語句的其他選項包括“INSERT...SET”語句、“INSERT...SELECT”語句以及其他一些選項。
注意 - 語句中出現的 VALUES() 函式僅適用於 INSERT 語句,如果在其他地方使用則返回 NULL。
執行此操作有兩種選擇:使用命令列或使用 PHP 指令碼。
命令提示符
在提示符下,可以透過多種方式執行選擇操作。下面給出一個標準語句:
belowmysql> INSERT INTO products_tbl (ID_number, Nomenclature) VALUES (12345,“Orbitron 4000”); mysql> SHOW COLUMNS FROM products_tbl; +-------------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------------+-------------+------+-----+---------+-------+ | ID_number | int(5) | | | | | | Nomenclature| char(13) | | | | | +-------------+-------------+------+-----+---------+-------+
您可以插入多行:
INSERT INTO products VALUES (1, “first row”), (2, “second row”);
您還可以使用 SET 子句:
INSERT INTO products SELECT * FROM inventory WHERE status = 'available';
PHP 插入指令碼
在 PHP 函式中使用相同的“INSERT INTO...”語句來執行該操作。您將再次使用mysql_query()函式。
檢視下面給出的示例:
<?php if(isset($_POST['add'])) { $dbhost = 'localhost:3036'; $dbuser = 'root'; $dbpass = 'rootpassword'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } if(! get_magic_quotes_gpc() ) { $product_name = addslashes ($_POST['product_name']); $product_manufacturer = addslashes ($_POST['product_name']); } else { $product_name = $_POST['product_name']; $product_manufacturer = $_POST['product_manufacturer']; } $ship_date = $_POST['ship_date']; $sql = "INSERT INTO products_tbl ". "(product_name,product_manufacturer, ship_date) ". "VALUES"."('$product_name','$product_manufacturer','$ship_date')"; mysql_select_db('PRODUCTS'); $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not enter data: ' . mysql_error()); } echo "Entered data successfully\n"; mysql_close($conn); } ?>
成功插入資料後,您將看到以下輸出:
mysql> Entered data successfully
您還可以將驗證語句與插入語句結合使用,例如檢查以確保正確的資料輸入。MariaDB 為此提供了許多選項,其中一些是自動的。
廣告