Skip to content

Instantly share code, notes, and snippets.

@tangyangzhe
Last active December 21, 2015 12:29
Show Gist options
  • Save tangyangzhe/6305895 to your computer and use it in GitHub Desktop.
Save tangyangzhe/6305895 to your computer and use it in GitHub Desktop.
PHP使用PDO操作MySQL
function getConnection() {
$dbhost="127.0.0.1";
$dbuser="root";
$dbpass="root";
$dbname="cellar";
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8';"));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
}
function deleteWine($id) {
$sql = "DELETE FROM wine WHERE id=:id";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("id", $id);
$stmt->execute();
$db = null;
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
function getWine($id) {
$sql = "SELECT * FROM wine WHERE id=:id";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("id", $id);
$stmt->execute();
$wine = $stmt->fetchObject();
$db = null;
echo json_encode($wine);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
function getWines() {
$sql = "select * FROM wine ORDER BY name";
try {
$db = getConnection();
$stmt = $db->query($sql);
$wines = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo '{"wine": ' . json_encode($wines) . '}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment