- 同样,利用
MySQLi
或者 PDO
向 MySQL
插入数据
- INSERT INTO 语句常用于向 MySQL 表添加新的记录:
INSERT INTO table_name(字段名1,字段名2,...) VALUES (value1, value2, value3,...)
插入数据要注意
- PHP 中
SQL
查询语句必须使用引号
- 在
SQL
查询语句中的字符串值必须加引号
- 数值的值不需要引号
-
NULL
值不需要引号
MySQLi 向 MySQL 插入数据
面向对象
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
$sql = "INSERT INTO LXJtable(firstname, lastname, email) VALUES ('新之助', '野原', 'lbxx@example.com')";
if ($conn->query($sql) === TRUE) {
echo "新记录插入成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
面向过程
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO LXJtable(firstname, lastname, email) VALUES ('新之助', '野原', 'lbxx@example.com')";
if (mysqli_query($conn, $sql)) {
echo "新记录插入成功";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
PDO向 MySQL 插入数据
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO LXJtable(firstname, lastname, email) VALUES ('新之助', '野原', 'lbxx@example.com')";
$conn->exec($sql);
echo "新记录插入成功";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>