我有一些古老的代码,我想将其转换为 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;
}
?>
最佳答案
好吧,准备好的语句非常棘手
(这就是为什么我更喜欢自制的占位符而不是准备好的语句)
首先,你必须让这个古老的代码变得合理,而不是当前的所有困惑。 每个参数只检查一次。
这是给你一个想法的代码
$w = array();
if ( !empty($_GET['c']) AND ($_GET['c'] == "1" ) || ( $_GET['c'] == "2") )
{
$w[] = $db->parse("GGG = ?i", $_GET['c']);
}
if ( isset($_GET['y']) && isset($_GET['m']) )
{
$w[] = $db->parse("where y = ?i and m = ?i",$_GET['y'],$_GET['m']);
}
$where = '';
if ($w) $where = implode(' AND ',$w);
$query = "select * from table1 $where";
要使用准备好的语句,您必须将值添加到数组中,然后将其与 execute() 一起使用
关于php - 使用 PDO 构建查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7611890/