PHP语法学习(第九天)—PHP连接mysql详解(下)-PHP MySQL 插入数据

时间:2024-12-10 21:16:34
  • 同样,利用MySQLi 或者 PDOMySQL 插入数据
  • INSERT INTO 语句常用于向 MySQL 表添加新的记录:
INSERT INTO table_name(字段名1,字段名2,...) VALUES (value1, value2, value3,...)

插入数据要注意

  1. PHP 中 SQL 查询语句必须使用引号
  2. SQL 查询语句中的字符串值必须加引号
  3. 数值的值不需要引号
  4. 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);
} 
//myql插入数据  
$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);
    // 设置 PDO 错误模式,用于抛出异常
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "INSERT INTO LXJtable(firstname, lastname, email) VALUES ('新之助', '野原', 'lbxx@example.com')";
    // 使用 exec() ,没有结果返回 
    $conn->exec($sql);
    echo "新记录插入成功";
}

catch(PDOException $e)
{
    echo $sql . "<br>" . $e->getMessage();
}
 $conn = null;
?>