首页 > 代码库 > MySQLi & PDO
MySQLi & PDO
MySQLi
<?php $servername = "localhost"; $username = "username"; $password = "password"; // 创建连接 $conn = new mysqli($servername, $username, $password); // 检测连接 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } echo "连接成功"; ?>
PDO
<?php $servername = "localhost"; $username = "username"; $password = "password"; try { $conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password); echo "连接成功"; } catch(PDOException $e) { echo $e->getMessage(); } ?>
关闭链接
实例 (MySQLi - 面向对象) $conn->close();
实例 (MySQLi - 面向过程) mysqli_close($conn);
实例 (PDO) $conn = null;
创建数据库
实例 (MySQLi - 面向对象) <?php $servername = "localhost"; $username = "username"; $password = "password"; // 创建连接 $conn = new mysqli($servername, $username, $password); // 检测连接 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } // 创建数据库 $sql = "CREATE DATABASE myDB"; if ($conn->query($sql) === TRUE) { echo "数据库创建成功"; } else { echo "Error creating database: " . $conn->error; } $conn->close(); ?>
实例 (MySQLi Procedural) <?php $servername = "localhost"; $username = "username"; $password = "password"; // 创建连接 $conn = mysqli_connect($servername, $username, $password); // 检测连接 if (!$conn) { die("连接失败: " . mysqli_connect_error()); } // 创建数据库 $sql = "CREATE DATABASE myDB"; if (mysqli_query($conn, $sql)) { echo "数据库创建成功"; } else { echo "Error creating database: " . mysqli_error($conn); } mysqli_close($conn); ?>
使用 PDO: <?php $servername = "localhost"; $username = "username"; $password = "password"; try { $conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password); // 设置 PDO 错误模式为异常 $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "CREATE DATABASE myDBPDO"; // 使用 exec() ,因为没有结果返回 $conn->exec($sql); echo "数据库创建成功<br>"; } catch(PDOException $e) { echo $sql . "<br>" . $e->getMessage(); } $conn = null; ?>
MySQLi & PDO
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。