首先基本配置:
连接MYSQL
<?php
$dsn = 'mysql:host=localhost;dbname=world;';
$user = 'user';
$password = 'secret';
try
{
$dbh = new PDO($dsn, $user, $password);
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
?>
连接SQLite
<?php
$dsn = 'sqlite2:"C:\sqlite\world.db"';
try
{
$dbh = new PDO($dsn);
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
?>
连接PostgreSQL
<?php
$dsn = 'pgsql:host=localhost port=5432 dbname=world user=user ';
$dsn .= 'password=secret';
try
{
$dbh = new PDO($dsn);
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
?>
端口:MySQL是 3306, PostgreSQL是 5432
第一步:怎样从数据库中获取数据
用query:
$country = 'USA';
try
{
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
$sql = 'Select * from city where CountryCode =' .
$dbh->quote($country);
foreach (
$dbh->query($sql)
as $row)
{
print $row['Name'] . "\t";
print $row['CountryCode'] . "\t";
print $row['Population'] . "\n";
}
}
catch (PDOException $e)
{
echo 'PDO Exception Caught.
';
echo 'Error with the database: <br />';
echo 'SQL Query: ', $sql;
echo 'Error: ' . $e->getMessage();
用Perpare和Execute
$country = 'USA';
try
{
$dbh = new PDO($dsn, $user, $password);
$sql = 'Select * from city where CountryCode =:country';
$dbh->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
$stmt =
$dbh->prepare($sql)
;
$stmt->bindParam(':country', $country, PDO::PARAM_STR);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
print $row['Name'] . "\t";
print $row['CountryCode'] . "\t";
print $row['Population'] . "\n";
}
}
catch (PDOException $e)
{
echo 'PDO Exception Caught. ';
echo 'Error with the database: <br />';
echo 'SQL Query: ', $sql;
echo 'Error: ' . $e->getMessage();
}
}
query、fecht和execute的比较:
query对只查询一次是比较有利的,多次查询用fetch和execute
fetch的选择内容:
假如想用面向对象的代码,可以使用fetchObject方法,顾名思义将返回对象,例如:
while ($row =$stmt->fetchObject())
{
print $row->Name . "\t";
print $row->CountryCode . "\t";
print $row->Population . "\n";
}
基本的pdo的操作就这些。