Blogger Information
Blog 26
fans 0
comment 3
visits 20539
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
mysql数据库一(连接方式)
无意苦争春的博客
Original
980 people have browsed it

 竹子熊    2017.9.20

 作为小白,一直被数据库的连接方式苦恼,于是决定找个时间梳理一下.

一.MYSQLi连接数据库处理

//1.连接数据库
//连接数据库并屏蔽错误信息
$link=@mysqli_connect('localhost','root','123456')or exit('数据库连接失败');
//2.设置字符集
mysqli_set_charset($link,'utf8');//成功返回true,失败返回false

二.PDO扩展

<?php
//设置字符集
header('Content-Type:text/html;charset=utf-8');
//设置数据库的DSN信息
$dsn='mysql:host=localhost;dbname=project;charset=utf8';
try{
    $pdo=new PDO($dsn,'root','123456');
}catch(PDOException $e){
    exit('PDO连接数据库失败:'.$e->getMessage());
}
//执行SQL语句
$sql='select `id`,`title`,`addtime`from `news`order by`addtime`desc';
$stmt=$pdo->query($sql);返回PDOStatement对象
//处理结果集
$data=$stmt->fetchAll(PDO::FETCH_ASSOC);//以关联数组返回

?>

pdo预处理机制

$data=array();
//连接数据库,执行sql语句,失败显示错误提示
requre'./init.php';
$sql='insert into `news`(`title`,`content`)values(:title,:content)';
$stmt=$pdo->prepare($sql);
if(!$stmt->execute($data)){
    exit('执行失败:'.implode('-',$stmt->errorInfo()));
}


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
1 comments
无意苦争春 2018-01-03 20:06:40
2333
1 floor
Author's latest blog post