我有一些古老的代碼,我要轉換爲PDO:使用PDO構建查詢?
<?php
function build_query() {
// db connection here
$the_query = "";
if (empty($_GET['c'])) {
$the_query = "select * from table1";
if ((isset($_GET['y'])) && (isset($_GET['m']))) {
$the_query .= " where y = " . $_GET['y'] . " and m = " . $_GET['m'];
}
} elseif (($_GET['c'] == "1") || ($_GET['c'] == "2")) {
$the_query = "select * from table1 where GGG = " . $_GET['c'];
if ((isset($_GET['y'])) && (isset($_GET['m']))) {
$the_query .= " and y = " . $_GET['y'] . " and m = " . $_GET['m'];
}
} else {
$the_query = "select * from table1";
if ((isset($_GET['y'])) && (isset($_GET['m']))) {
$the_query .= " where y = " . $_GET['y'] . " and m = " . $_GET['m'];
}
$the_query .= " and c = " . $_GET['c'];
}
return // use the query to return results $the_data;
}
?>
我似乎無法弄清楚如何重新編寫此使用PDO。我做了下面一個開始,但似乎無法得到任何進一步:
<?php
function build_query() {
$the_data = "";
$DBH = new PDO("mysql:host=server;dbname=database", "user", "pass");
$DBH -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$STH = $DBH -> prepare("build query here");
$STH -> bindParam(':c', $_GET['c'], PDO::PARAM_INT);
$STH -> bindParam(':y', $_GET['y'], PDO::PARAM_INT);
$STH -> bindParam(':m', $_GET['m'], PDO::PARAM_INT);
$STH -> execute();
$ROWS = $STH -> fetchAll();
foreach($ROWS as $ROW) {
$output .= $ROW["a"] . " - " . $ROW["b"] . " - " . $ROW["c"] . " - " . $ROW["d"] . "<br />";
}
$DBH = null;
return $output;
}
?>
你真的連接到預處理語句數據庫每次運行查詢時? –
@Col。據我所知,彈片是的。 – oshirowanen
但爲什麼?有什麼理由呢?僅僅因爲它在教程中? –