Blogger Information
Blog 55
fans 0
comment 0
visits 50508
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PHP中mysqli操作连接数据库
Bean_sproul
Original
688 people have browsed it

方法一

实例

<?php 
//创建一个数据库连接,并返回mysqli对象

error_reporting(E_ALL ^E_WARNING);//将警告忽略掉
$mysqli = new mysqli('127.0.0.1','root','root');

// var_dump($mysqli);打印测试连接



//判断是否连接成功
if ($mysqli->connect_errno){
	//自定义错误提示
	die('连接错误'.$mysqli->connect_errno.':'.$mysqli->connect_error);
}


 $mysqli->select_db('work');//设置默认数据库

 $mysqli->set_charset('utf8');

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

 ?>

运行实例 »

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

方法二 将连接参数转为变量

实例

<?php 
//创建一个数据库连接,并返回mysqli对象

//简化:将连接参数转为变量或数组

$db_host ='127.0.0.1';
$db_user ='root';
$db_pass ='root';
$db_name ='work';
$db_charset ='utf8';

error_reporting(E_ALL ^E_WARNING);//将警告忽略掉
$mysqli = new mysqli($db_host,$db_user,$db_pass);

// var_dump($mysqli);打印测试连接

//判断是否连接成功
if ($mysqli->connect_errno){
	//自定义错误提示
	die('连接错误'.$mysqli->connect_errno.':'.$mysqli->connect_error);
}


 $mysqli->select_db($db_name);//设置默认数据库

 $mysqli->set_charset($db_charset);

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

 ?>

运行实例 »

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

方法三 将连接参数转为数组


实例

<?php 
//创建一个数据库连接,并返回mysqli对象

//简化:将连接参数转为变量或数组

$db = [
		$db_host ='127.0.0.1',
		$db_user ='root',
		$db_pass ='root',
		$db_name ='work',
		$db_charset ='utf8'
]

error_reporting(E_ALL ^E_WARNING);//将警告忽略掉
$mysqli = new mysqli($db['host'],$db['user'],$db['pass']);

// var_dump($mysqli);打印测试连接

//判断是否连接成功
if ($mysqli->connect_errno){
	//自定义错误提示
	die('连接错误'.$mysqli->connect_errno.':'.$mysqli->connect_error);
}


 $mysqli->select_db($db['name']);//设置默认数据库

 $mysqli->set_charset($db['charset']);

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

 ?>

运行实例 »

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

 

Correction status:Uncorrected

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