Blogger Information
Blog 27
fans 1
comment 2
visits 25177
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
数据库的连接方式与查询操作(4月24日16时30分)
一枝黄花
Original
636 people have browsed it

数据库的连接方式:

mysqli数据库连接

 * 步骤:

 * 1. 创建连接参数

 * 2. 调用连接函数,返回连接资源

 * 3. 判断是否连接成功

 * 4. 选择数据库

 * 5. 设置默认字符集

代码实例

//1.创建一个连接参数

define ('DB_HOST', 'localhost');

define('DB_USER','root');

define('DB_PASS','root')

define('DB_NAME','php');

define('DB_CHAR','utf8');



//2.调用链接函数,返回链接资源

$db = @mysqli_connect(DB_HOST, DB_USER, DB_PASS);



//3.判断是否连接成功

if (mysqli_connect_errno($db)){

exit('连接失败'.mysqli_connect_errno($db));



}

echo'<h1>连接成功</h1>';



//4.选择数据库

mysqli_select_db($db,DB_NAME);



//5.设置默认字符集

mysqli_select_charSET($db,DB_CHAR);

运行实例 »

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

数据库查询执行操作

实例

//1.连接数据库
require 'mysqli_connect.php';

//2.准备SQL语句
$sql = "SELECT name,salary FROM staff";

//3.执行查询:成功会返回结果集对象,失败返回false
if ($result = mysqli_query($db, $sql)){
    if (mysqli_num_rows($result) > 0) {
        while($row = mysqli_fetch_assoc($result)) {
            var_export(print_r($row),true);
            echo '<hr>';
        }
    }
} else {
    exit(mysqli_errno($db).':'.mysqli_error($db));
}

//4.释放结果集(仅针对select)
mysqli_free_result($result);

//5.关闭数据库连接
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