PDO连接数据库,方式一
<?php
//数据源
$dsn = "mysql:dbname=test;host=localhost";
//异常
try
{
//实例化
$pdo = new PDO($dsn,"root","mysql123");
echo "connect database ok.<br>\n";
//查询语句
$sql = "select * from user";
//设置字符集
$pdo->query("set names utf8");
//循环取值
foreach ($pdo->query($sql) as $row)
{
print_r($row);
echo "<br>\n";
}
}
//捕获异常
catch (PDOException $e)
{
echo "connect database failed.<br>\n";
print_r($e);
}
PDO连接数据库,方式二
<?php
//数据源
$dsn = "mysql:dbname=test;host=localhost";
//异常
try
{
//实例化
$pdo = new PDO($dsn,"root","mysql123");
echo "connect database ok.<br>";
//查询语句
$sql = "select * from user";
//设置字符集
$pdo->query("set names utf8");
//执行查询
$result = $pdo->query($sql);
//取值,返回数组
while($row = $result->fetch(PDO::FETCH_ASSOC))
{
print_r($row);
}
}
//捕获异常
catch (PDOException $e)
{
echo "connect database failed.<br>\n";
print_r($e);
}
PDO连接数据库,获取错误码
<?php
$dsn = "mysql:dbname=test;host=localhost";
try
{
$pdo = new PDO($dsn,"root","mysql123");
}
catch (PDOException $e)
{
echo "connect database failed.".$e->getMessage()."<br>";
}
//此表不存在
$sql = "insert into p values(null,'1','2')";
$pdo->exec($sql);
//获取错误码
echo "error:".$pdo->errorCode();
PDO连接数据库,获取错误详细信息
<?php
//数据源
$dsn = "mysql:dbname=test;host=localhost";
//异常
try
{
$pdo = new PDO($dsn,"root","mysql123");
$sql = "select bbb from user";
$pdo->query("set names utf8");
$pdo->query($sql);
//异常码
echo "errorcode:";
echo $pdo->errorCode();
echo "<br>\n";
//异常详细信息
echo "errorinfo:";
print_r($pdo->errorInfo());
}
catch (PDOException $e)
{
echo $e->getMessage();
}