PHP数据库连接
PHP连接Mysql方式
MySQLi extension ("i" 意为 improved)
PDO (PHP Data Objects)
PDO 应用在 12 种不同数据库中, MySQLi 只针对 MySQL 数据库。
phpinfo() 查看是否安装PDO
php代码
连接数据库
<?php
//MySQLi - 面向对象
$servername = "localhost";
$username = "root";
$password = "root";
// 创建连接
$conn = new mysqli($servername, $username, $password);
// 检测连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
echo "连接成功";
//MySQLi - 面向过程
// 创建连接
$conn = mysqli_connect($servername, $username, $password);
// 检测连接
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "连接成功";
//PDO
try {
$conn = new PDO("mysql:host=$servername;", $username, $password);
echo "连接成功";
} catch (PDOException $e) {
echo $e->getMessage();
}
/*关闭对象*/
//MySQLi - 面向对象
$conn->close();
//MySQLi - 面向过程
mysqli_close($conn);
//PDO
$conn = null;
PDO增删改查
<?php
$host = '127.0.0.1';
$db = 'autumn';
$user = 'root';
$pass = 'root';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
// Create
function createUser($name) {
global $pdo;
$sql = "INSERT INTO user (name) VALUES (?)";
$stmt= $pdo->prepare($sql);
$stmt->execute([$name]);
echo "User Created\n";
}
// Read
function getUser($id) {
global $pdo;
$sql = "SELECT * FROM user WHERE id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$id]);
$user = $stmt->fetch();
print_r($user);
}
// Update
function updateUser($id, $name) {
global $pdo;
$sql = "UPDATE user SET name = ? WHERE id = ?";
$stmt= $pdo->prepare($sql);
$stmt->execute([$name, $id]);
echo "User Updated\n";
}
// Delete
function deleteUser($id) {
global $pdo;
$sql = "DELETE FROM user WHERE id = ?";
$stmt= $pdo->prepare($sql);
$stmt->execute([$id]);
echo "User Deleted\n";
}
// 使用示例
createUser('John Doe');
getUser(1);
updateUser(1, 'Jane Doe');
deleteUser(1);
?>
如果这篇文章对你有用,可以关注本人微信公众号获取更多ヽ(^ω^)ノ ~
![微信公众号二维码](https://images.cnblogs.com/cnblogs_com/aeolian/1679458/o_wechat_gzh_qrcode.jpg)