使用PDO构建查询?

时间:2011-09-30 14:32:42

标签: php mysql 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; 
    }       
?>

2 个答案:

答案 0 :(得分:2)

嗯,准备好的陈述是非常棘手的 (这就是为什么我更喜欢我的家庭酿造占位符而不是准备好的陈述)

首先,你必须让这个古老的代码变得明智,没有当前的混乱。 仅检查每个参数一次。

这是一个给你一个想法的代码

$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()

一起使用

答案 1 :(得分:0)

您正在改变您的功能,以便做更多的事情。如果你想坚持原始设计(这与你的函数名称一致...),你需要更改你的函数,使它仍然返回一个查询但不执行它,因为旧版本没有连接到数据库或查询数据库。

要解决您的问题,您可以让函数返回一个包含2个元素的数组,带有命名参数的查询和另一个带有名称 - 值对的数组。

如果您确实想要返回查询结果,可以使用全局变量进行数据库连接,或将其作为变量传递给函数。