php pdo 类 方法有哪些

php pdo类方法有:1、exec方法;2、query方法;3、lastInsertId方法;4、setAttribute方法等等。

推荐:《PHP视频教程》

pdo类常用方法:

exec()

query()

lastInsertId()

<?php
$servername = "localhost";
$username = "root";
$password = "133nubia022";
$dbname='myweb';

$pdo= new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$pdo->exec('set names utf8');

$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_BOTH);

$sql="insert into user(username,age) values('user123','55')";

if($pdo->exec($sql)){
	$lastid=$pdo->lastInsertId();
	echo "ID为{$lastid}的数据插入成功!";
}
?>

在这里插入图片描述

• setAttribute()


设置获取模式属性

<?php
$servername = "localhost";
$username = "root";
$password = "133nubia022";
$dbname='myweb';
 

$pdo= new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);

$pdo->exec('set names utf8');
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);

$sql="select * from user";

$smt=$pdo->query($sql);
$rows=$smt->fetchAll();

echo '<pre>';
print_r($rows);
echo '</pre>';
?>

在这里插入图片描述***
获取索引数组

<?php
$servername = "localhost";
$username = "root";
$password = "133nubia022";
$dbname='myweb';

$pdo= new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$pdo->exec('set names utf8');

$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_NUM);

$sql="select * from user";
$smt=$pdo->query($sql);
$rows=$smt->fetchAll();

echo '<pre>';
print_r($rows);
echo '</pre>';
?>

在这里插入图片描述


获取混合数组

<?php
$servername = "localhost";
$username = "root";
$password = "133nubia022";
$dbname='myweb';

$pdo= new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$pdo->exec('set names utf8');

$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_BOTH);

$sql="select * from user";
$smt=$pdo->query($sql);
$rows=$smt->fetchAll();

echo '<pre>';
print_r($rows);
echo '</pre>';
?>

在这里插入图片描述

hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 » php pdo 类 方法有哪些