第一天 pdo

================连接数据库======================

header('Content-Type:text/html; charset=utf-8');

error_reporting(E_ALL^E_NOTICE);

try{

$pdo_conn=new PDO('mysql:host=localhost;dbname=study_test','root','');

}catch(PDOException $e){

echo 'conn error'.$e->getMessage();

}

$pdo_conn->exec('set names utf8;');

==================PDO 增 删 改======================

$pdo_conn->exec($sql);

====================PDO  查===========================

<?php

header("content-type:text/html;charset=utf-8");

// 创建pdo对象

$pdo=new PDO("mysql:host=localhost;dbname=php72idc","php72idccn","yA0j9V5TOwMgo1R7UcJrMPAru36O5");

$sql="select id,name,sex from test";

// pdo查询得到结果集

$stmt=$pdo->query($sql);

// fetchAll  从结果集中获得数组

$array=$stmt->fetchAll(PDO::FETCH_ASSOC);

/*

PDO::FETCH_ASSOC    转化为关联数组

PDO::FETCH_BOTH     转化为索引关联数组

*/

var_dump($array);

foreach ($array as $item) {

// var_dump($item);

echo $item['id'],$item['name'],$item['sex'];

echo "<hr>";

}

?>

================================================

联表查询

SELECT * FROM  A AS a

INNER JOIN  B AS b  ON a.id=b.bid

INNER JOIN C AS c   ON  b.id=c.cid

WHERE 1;

====================================================

fetchAll  -->获取所有查询结果

fetch   --->获取一条查询记录

<?php

header("content-type:text/html;charset=utf-8");

// 创建pdo对象

$pdo=new PDO("mysql:host=localhost;dbname=php72idc","php72idccn","yA0j9V5TOwMgo1R7UcJrMPAru36O5");

$sql="select id,name,sex from test";

// pdo查询得到结果集

$stmt=$pdo->query($sql);

// fetch  查询一条结果 如查询出多条记录,默认取得第一条

$array=$stmt->fetch(PDO::FETCH_ASSOC);

/*

PDO::FETCH_ASSOC    转化为关联数组

PDO::FETCH_BOTH     转化为索引关联数组

*/

var_dump($array);

?>

====================================================

<?php

header("content-type:text/html;charset=utf-8");

// 创建pdo对象

$pdo=new PDO("mysql:host=localhost;dbname=php72idc","php72idccn","yA0j9V5TOwMgo1R7UcJrMPAru36O5");

$sql="select id,name,sex from test";

// pdo查询得到结果集

$stmt=$pdo->query($sql);

// setFetchMode() 获取模式

// fetch  查询一条结果 如查询出多条记录,默认取得第一条

$stmt->setFetchMode(PDO::FETCH_ASSOC);//很多时候不使用这个模式,是指直接$array=$stmt->fetch(PDO::FETCH_ASSOC);

$array=$stmt->fetch();

// $array=$stmt->fetch(PDO::FETCH_ASSOC);

/*

PDO::FETCH_ASSOC    转化为关联数组

PDO::FETCH_BOTH     转化为索引关联数组

*/

var_dump($array);

?>

(0)

相关推荐