php - 使用 PDO 构建查询?

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

最佳答案

好吧,准备好的语句非常棘手
(这就是为什么我更喜欢自制的占位符而不是准备好的语句)

首先,你必须让这个古老的代码变得合理,而不是当前的所有困惑。 每个参数只检查一次。

这是给你一个想法的代码

$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/

相关文章:

javascript - Laravel 5.3 包含 JS 插件,例如 jQuery

php - 关闭页面后脚本会继续运行吗?

php - 在此上下文中,元素 p 不允许作为元素 dl 的子元素。 (抑制来自该子树的更多错误。)

mysql - 如何在经典 ASP/VBScript 中处理部分零日期(即 2010-04-00)?

php - 如何从字符串中删除这个多余的字符?

php - 对多维数组使用 array_search

php - PDO 绑定(bind)日期 MYSQL - 如何传递日期?

php - 如何使用HTML和PHP创建一个只有一个提交按钮的多表单搜索功能?

php - PDOException “could not find driver”

php - 无效数据源 PHP PDO Mysql