PHP 的数据连接方式

2022/3/28 17:23:06

本文主要是介绍PHP 的数据连接方式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

PHP与MySQL的连接有三种方式,分别是:PHP的MySQL扩展 、PHP的mysqli扩展 、PHP数据对象(PDO) ,下面针对以上三种连接方式做下总结,以备在不同场景下选出最优方案。

   1、PHP的MySQL扩展是设计开发允许php应用与MySQL数据库交互的早期扩展。MySQL扩展提供了一个面向过程的接口,并且是针对MySQL4.1.3或者更早版本设计的。因此这个扩展虽然可以与MySQL4.1.3或更新的数据库服务端进行交互,但并不支持后期MySQL服务端提供的一些特性。由于太古老,又不安全,所以已被后来的mysqli完全取代。示例:
<?php
    $mysql_conn = @mysql_connect('127.0.0.1:3306','root','root@123');
    if (!$mysql_conn) {
        die("could not connect to the database:\n" . mysql_error());//诊断连接错误
    }
    mysql_query("set names 'utf8'");//编码转化
    $select_db = mysql_select_db('mydb');
    if (!$select_db) {
        die("could not connect to the db:\n" .  mysql_error());
    }
    $sql = "select * from user;";
    $res = mysql_query($sql);
    if (!$res) {
        die("could get the res:\n" . mysql_error());
    }
    while ($row = mysql_fetch_assoc($res)) {
        print_r($row);
    }
    mysql_close($mysql_conn);
?>
   2、PHP的mysqli扩展,我们有时称之为MySQL增强扩展,可以用于使用 MySQL4.1.3或更新版本中新的高级特性。其特点为:面向对象接口 、prepared语句支持、多语句执行支持、事务支持 、增强的调试能力、嵌入式服务支持 、预处理方式完全解决了sql注入的问题。不过其也有缺点,就是只支持mysql数据库。如果你要是不操作其他的数据库,这无疑是最好的选择。示例:
<?php
    // 方式一
    $mysqli = @new mysqli('127.0.0.1:3306','root','root@123');
    if ($mysqli->connect_errno) {
        die("could not connect to the database:\n" . $mysqli->connect_error);//诊断连接错误
    }
    $mysqli->query("set names 'utf8';");//编码转化
    $select_db = $mysqli->select_db('mydb');
    if (!$select_db) {
        die("could not connect to the db:\n" .  $mysqli->error);
    }
    $sql = "select uid from user where name = 'joshua';";
    $res = $mysqli->query($sql);
    if (!$res) {
        die("sql error:\n" . $mysqli->error);
    }
    while ($row = $res->fetch_assoc()) {
        var_dump($row);
    }
    $res->free();
    $mysqli->close();
// 方式二
```
$conn = mysqli_connect('127.0.0.1','root','root@123','mydb', 3306);
if (!$conn) {
    die('连接错误: ' . mysqli_connect_error());
}
$sql = "select uid from user where name = 'joshua'";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
    var_dump($row);
}

?>

       3、PDO是PHP Data Objects的缩写,是PHP应用中的一个数据库抽象层规范。PDO提供了一个统一的API接口可以使得你的PHP应用不去关心具体要连接的数据库服务器系统类型,也就是说,如果你使用PDO的API,可以在任何需要的时候无缝切换数据库服务器,比如从Oracle 到MySQL,仅仅需要修改很少的PHP代码。其功能类似于JDBC、ODBC、DBI之类接口。同样,其也解决了sql注入问题,有很好的安全性。不过他也有缺点,某些多语句执行查询不支持(不过该情况很少)。示例:
exec("set names 'utf8'"); $sql = "select * from user where name = ?"; $stmt = $pdo->prepare($sql); $stmt->bindValue(1, 'zhansan', PDO::PARAM_STR); $rs = $stmt->execute(); if ($rs) { // PDO::FETCH_ASSOC 关联数组形式 // PDO::FETCH_NUM 数字索引数组形式 while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { var_dump($row); } } $pdo = null;//关闭连接 ?>
————————————————
版权声明:本文为CSDN博主「鹤啸九天-西木」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/lzghxjt/article/details/87606078


这篇关于PHP 的数据连接方式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程