- 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 为此提供了许多选项,其中一些是自动的。
广告