Created
November 25, 2015 16:25
-
-
Save zyzsdy/e7ca723e7bea30c8274e to your computer and use it in GitHub Desktop.
PHP PDO Tutorial example code.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* PHP PDO Tutorial | |
* Author: zyzsdy <[email protected]> | |
* Github: https://github.com/zyzsdy | |
*/ | |
$DB_INFO = array( | |
'type' => 'mysql', | |
'host' => 'localhost', | |
'port' => '3306', | |
'schema' => 'wikiplus', | |
'username' => 'root', | |
'password' => '', | |
); | |
$DB_DSN = $DB_INFO['type'] . ":host=" . $DB_INFO['host'] | |
. ";port=" . $DB_INFO['port'] . ";dbname=" . $DB_INFO['schema']; | |
$PDO_ATTR = array( | |
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'", | |
); | |
try { | |
$db = new PDO($DB_DSN, $DB_INFO['username'], $DB_INFO['password'], $PDO_ATTR); | |
} catch (PDOException $e) { | |
die('数据库连接失败,错误原因:' . $e->getMessage()); | |
} | |
$wikiName = "Wikipedia"; | |
try { | |
$sql = $db->prepare("SELECT * FROM `wikiplus_statistics` WHERE `wikiname`=:wikiname | |
ORDER BY `id` DESC LIMIT 10"); | |
$sql->bindParam(':wikiname', $wikiName); | |
$sql->execute(); | |
$rows = $sql->fetchAll(PDO::FETCH_ASSOC); | |
foreach($rows as $row){ | |
//echo $row['id'] . "\t" . $row['pagename'] . "\n"; | |
} | |
} catch (PDOException $e){ | |
die('数据库查询失败,错误原因:' . $e->getMessage()); | |
} | |
try { | |
$sql2 = $db->prepare("SELECT * FROM `wikiplus_statistics` WHERE `wikiname` = ? AND `username` = ? | |
ORDER BY `id` DESC LIMIT 10"); | |
$sql2->execute(array("萌娘百科", "妹空酱")); | |
$res = $sql2->fetchAll(PDO::FETCH_ASSOC); | |
foreach($res as $row){ | |
echo $row['id'] . "\t" . $row['pagename'] . "\n"; | |
} | |
} catch (PDOException $e){ | |
die('数据库查询失败,错误原因:' . $e->getMessage()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment