Blogger Information
Blog 14
fans 1
comment 1
visits 9580
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
MySQL数据库的连接与查询--2018年4月23日
雪风02的博客
Original
612 people have browsed it

一.数据库的连接:

实例

<?php
/医院
 * 配置数据库连接参数
 */

define ('DB_HOST', 'localhost');
define ('DB_USER', 'root');
define ('DB_PASS', '');
define ('DB_NAME', 'php');
define ('DB_CHAR', 'utf8');

运行实例 »

点击 "运行实例" 按钮查看在线实例


实例

<?php
/医院
 * mysqli数据库连接简化版
 */

//1.导入数据库连接参数
require 'mysqli_config.php';

//2. 调用连接函数,返回连接资源
$db = @mysqli_connect(DB_HOST, DB_USER, DB_PASS,DB_NAME) or die('连接失败'.mysqli_connect_error($db));

//3. 设置默认字符集
mysqli_set_charset($db, DB_CHAR);

运行实例 »

点击 "运行实例" 按钮查看在线实例

调用连接函数返回连接对象,成功则返回mysqli对象,失败返回false;

比如: $db=mysqli_connect(DB_HOST,DB_USER,DB_PASS);



二.数据库的查询:

mysqli_query()

连接数据库:比如:require 'mysqli_connect.php';

 编写查询语句:比如:$sql="select * from students";

 执行查询:比如:if($res=mysqli_query($db,$sql)){

while($row=mysqli_fetch_array($res,MYSQLI_ASSOC)){

var_export($row); echo '<hr>';}

}else{

exit('查询失败'.mysqli_errno($db).mysqli_connect_error($db));

}

释放结果集:比如:mysqli_free_result($res);

  关闭数据库的连接:比如:mysqli_close($db);


实例

require 'mysqli_connect.php';


//2.执行查询
if($res = mysqli_query($db, "SELECT name,salary FROM staff")) {
    while($row = mysqli_fetch_assoc($res)) {
        var_export($row);
        print '<hr>';
    }
} else {
    exit('查询失败'.mysqli_errno($db).':'.mysqli_error($db));
}

//释放结果集(仅针对select)
mysqli_free_result($res);

//4.关闭数据库连接
mysqli_close($db);

运行实例 »

点击 "运行实例" 按钮查看在线实例


Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post