Blogger Information
Blog 31
fans 3
comment 1
visits 34584
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
mysql数据库连接和查询的基本步骤
php学习笔记
Original
1314 people have browsed it

一、数据库连接操作

<?php
//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_error($db));
}
//4.选择要操作的数据库
mysqli_select_db($db,DB_NAME);
//5.设置默认字符集
mysqli_set_charset($db,DB_CHAR);

二、数据库查询操作

<?php
//1.连接数据库
require 'mysqli_connect.php';
//2.准备查询的sql语句
$sql = "SELECT `user_id`,`user_name`,`email` FROM user";
//3.执行查询
$res = mysqli_query($db,$sql);
//4.检测结果集是否存在
if(false!=$res){
	if(mysqli_num_rows($res)>0){
		while($row = mysqli_fetch_array($res,MYSQLI_ASSOC)){
			var_export($row);
			print '<hr>';
		}
	}else{
		exit('没有查询到符合条件的数据');
	}
}else{
	exit('查询失败'.mysqli_errno($db).':'.mysqli_error($db));
}

运行结果:

1.png

2.png

3.png

总结:

数据库连接操作步骤:

  1. 创建连接参数

  2. 连接数据库

  3. 测试连接是否成功

  4. 选择要操作的数据库

  5. 设置默认字符集

数据库查询操作步骤:

  1. 连接数据库

  2. 准备查询的sql语句

  3. 执行查询

  4. 检测结果集是否存在

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