PHP MySQL 插入数据
Insert Data Into MySQL Using MySQLi and PDO
After a database and a table have been created, we can start adding data in them.
Here are some syntax rules to follow:
- The SQL query must be quoted in PHP
- String values inside the SQL query must be quoted
- Numeric values must not be quoted
- The word NULL must not be quoted
The INSERT INTO statement is used to add new records to a MySQL table:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
To learn more about SQL, please visit our SQL tutorial.
In the previous chapter we created an empty table named "MyGuests" with five columns: "id", "firstname", "lastname", "email" and "reg_date". Now, let us fill the table with data.
笔记: If a column is AUTO_INCREMENT (like the "id" column) or TIMESTAMP with default update of current_timesamp (like the "reg_date" column), it is no need to be specified in the SQL query; MySQL will automatically add the value.
The following examples add a new record to the "MyGuests" table:
示例(MySQLi 面向对象)
<?php
$服务器名称 = “本地主机”;
$用户名 = “用户名”;
$password = "密码";
$dbname = "myDB";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
如果 ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} 别的 {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->关闭();
?>
示例(MySQLi 过程)
<?php
$服务器名称 = “本地主机”;
$用户名 = “用户名”;
$password = "密码";
$dbname = "myDB";
// 创建连接
$conn = mysqli_connect($servername, $username, $password, $dbname);
// 检查连接
如果(!$ conn){
die("连接失败: " . mysqli_connect_error());
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
如果(mysqli_query($conn,$sql)){
echo "New record created successfully";
} 别的 {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
示例 (PDO)
<?php
$服务器名称 = “本地主机”;
$用户名 = “用户名”;
$password = "密码";
$dbname = "myDBPDO";
尝试 {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// 将 PDO 错误模式设置为异常
$conn->设置属性(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
// 使用 exec() 因为没有返回结果
$conn->执行($sql);
echo "New record created successfully";
} 捕获(PDOException $e){
回显$sql”。<br> “.$e->获取消息();
}
$conn = 空;
?>