PHP5.5 mysqli如何连接MySQL数据库和读取数据

在学习 1. 开启PHP的API支持

(1)首先修改您的php.ini的配置文件。
查找下面的语句:
;extension=php_mysqli.dll
将其修改为:
extension=php_mysqli.dll

(2)重新启动Apache/IIS,即可。

(3)说明:PHP需要单独的文件来支持这个扩展库,一般在PHP目录下的ext目录里能找到php_mysqli.dll文件(PHP <= 5.0.2 中是 libmysqli.dll),当然,在PHP的配置文件当中要有正确指向ext的信息(extension_dir)。假若您的PHP没有这个文件,您可以去下载PHP5的源码包。另外,这个API扩展,只能在PHP5以上版本使用。其它具体信息,请看下面。

 

2.PHP mysqli身份证

mysqli是“MySQL, Improved”的缩写,该扩展仅适用于PHP 5。它能用于mysql 4.1.1和更高版本。该扩展完全支持MySQL 5.1中采用的鉴定协议,也支持预处理语句和多语句API。此外,该扩展还提供了先进的、面向对象的编程接口

 

 

[html] view plain copy
 
  1. <?php     
  2.         
  3.     /* Connect to a MySQL server  连接数据库服务器 */     
  4.     $link = mysqli_connect(     
  5.                 'localhost',  /* The host to connect to 连接MySQL地址 */     
  6.                 'user',      /* The user to connect as 连接MySQL用户名 */     
  7.                 'password',  /* The password to use 连接MySQL密码 */     
  8.                 'world');    /* The default database to query 连接数据库名称*/     
  9.         
  10.     if (!$link) {     
  11.        printf("Can't connect to MySQL Server. Errorcode: %s ", mysqli_connect_error());     
  12.        exit;     
  13.     }     
  14.         
  15.     /* Send a query to the server 向服务器发送查询请求*/     
  16.     if ($result = mysqli_query($link, 'SELECT Name, Population FROM City ORDER BY Population DESC LIMIT 5')) {     
  17.         
  18.         //print("Very large cities are: ");     
  19.         
  20.         /* Fetch the results of the query 返回查询的结果 */     
  21.         while( $row = mysqli_fetch_assoc($result) ){     
  22.             printf("%s (%s) ", $row['Name'], $row['Population']);     
  23.         }     
  24.         
  25.         /* Destroy the result set and free the memory used for it 结束查询释放内存 */     
  26.         mysqli_free_result($result);     
  27.     }     
  28.         
  29.     /* Close the connection 关闭连接*/     
  30.     mysqli_close($link);     
  31.     ?>   

 

 

 

使用 MySQLi

 

以下实例中我们从 myDB 数据库的 MyGuests 表读取了 id, firstname 和 lastname 列的数据并显示在页面上:

 

 

[html] view plain copy
 
  1. <?php  
  2. $servername = "localhost";  
  3. $username = "username";  
  4. $password = "password";  
  5. $dbname = "myDB";  
  6.    
  7. // 创建连接  
  8. $conn = new mysqli($servername, $username, $password, $dbname);  
  9. // Check connection  
  10. if ($conn->connect_error) {  
  11.     die("连接失败: " . $conn->connect_error);  
  12. }   
  13.    
  14. $sql = "SELECT id, firstname, lastname FROM MyGuests";  
  15. $result = $conn->query($sql);  
  16.    
  17. if ($result->num_rows > 0) {  
  18.     // 输出数据  
  19.     while($row = $result->fetch_assoc()) {  
  20.         echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";  
  21.     }  
  22. } else {  
  23.     echo "0 结果";  
  24. }  
  25. $conn->close();  
  26. ?>  

 

 

以上代码解析如下:

首先,我们设置了 SQL 语句从 MyGuests数据表中读取 id, firstname 和 lastname 三个字段。之后我们使用改 SQL 语句从数据库中取出结果集并赋给复制给变量 $result。

函数 num_rows() 判断返回的数据。

如果返回的是多条数据,函数 fetch_assoc() 将结合集放入到关联数组并循环输出。 while() 循环出结果集,并输出 id, firstname 和 lastname 三个字段值。

以下实例使用 MySQLi 面向过程的方式,效果类似以上代码:

 

 

实例 (MySQLi - 面向过程)

[html] view plain copy
 
  1. <?php  
  2. $servername = "localhost";  
  3. $username = "username";  
  4. $password = "password";  
  5. $dbname = "myDB";  
  6.    
  7. // 创建连接  
  8. $conn = mysqli_connect($servername, $username, $password, $dbname);  
  9. // Check connection  
  10. if (!$conn) {  
  11.     die("连接失败: " . mysqli_connect_error());  
  12. }  
  13.    
  14. $sql = "SELECT id, firstname, lastname FROM MyGuests";  
  15. $result = mysqli_query($conn, $sql);  
  16.    
  17. if (mysqli_num_rows($result) > 0) {  
  18.     // 输出数据  
  19.     while($row = mysqli_fetch_assoc($result)) {  
  20.         echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";  
  21.     }  
  22. } else {  
  23.     echo "0 结果";  
  24. }  
  25.    
  26. mysqli_close($conn);  
  27. ?>  



 

 

使用 PDO (+ 预处理)

 

以下实例使用了预处理语句。

选取了 MyGuests 表中的 id, firstname 和 lastname 字段,并放到 HTML 表格中:

 

 

[html] view plain copy
 
    1. <?php  
    2. echo "<table style='border: solid 1px black;'>";  
    3. echo "<tr><th>Id</th><th>Firstname</th><th>Lastname</th></tr>";  
    4.    
    5. class TableRows extends RecursiveIteratorIterator {  
    6.     function __construct($it) {   
    7.         parent::__construct($it, self::LEAVES_ONLY);   
    8.     }  
    9.    
    10.     function current() {  
    11.         return "<td style='width:150px;border:1px solid black;'>" . parent::current(). "</td>";  
    12.     }  
    13.    
    14.     function beginChildren() {   
    15.         echo "<tr>";   
    16.     }   
    17.    
    18.     function endChildren() {   
    19.         echo "</tr>" . "\n";  
    20.     }   
    21. }   
    22.    
    23. $servername = "localhost";  
    24. $username = "username";  
    25. $password = "password";  
    26. $dbname = "myDBPDO";  
    27.    
    28. try {  
    29.     $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);  
    30.     $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);  
    31.     $stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests");   
    32.     $stmt->execute();  
    33.    
    34.     // 设置结果集为关联数组  
    35.     $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);   
    36.     foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {   
    37.         echo $v;  
    38.     }  
    39. }  
    40. catch(PDOException $e) {  
    41.     echo "Error: " . $e->getMessage();  
    42. }  
    43. $conn = null;  
    44. echo "</table>";  
    45. ?>  

posted on 2017-08-21 17:22  跳动的汗水  阅读(510)  评论(0编辑  收藏  举报

导航