douwo1517 2012-12-05 13:09
浏览 38
已采纳

如何以“可重用”的方式将参数传递给数组中的PDO SELECT语句?

I'm new to PDO and have successfully converted most of my site's inserts and updates to PDO transactions, each in a centrally accessible function for maximum reuse. I really want to do the same with the SELECT statements, but this seems harder!

What I was expecting to do is this:

function getProdDetails2SaveInInvoice($data) {

    global $dbh;

    try {
        $sth=$dbh->prepare("
        SELECT
            AES_DECRYPT(?, '".DBKEY,"'),
            AES_DECRYPT(?, '".DBKEY,"'),
            AES_DECRYPT(?, '".DBKEY,"')
         FROM
            products
        WHERE
            ? ? ?
    ");

        $sth->execute($data);
        $sth->fetch(PDO::FETCH_OBJ);

        return $sth;
    }

    catch(PDOException $e) {
        echo  "Something went wrong. Please report this error.
";
        file_put_contents(
            $_SERVER['DOCUMENT_ROOT']."/PDOErrors.txt",
            "

Script name : ".SCRIPT."
Function name : ".__FUNCTION__."
".
            $e->getMessage(), FILE_APPEND);

        throw new failedTransaction();
    }
}

// Fetch additional info from invoice_products.
        $data = array(
            'alt_id',           /* field 1                  */
            'prod_name',        /* field 2                  */
            'prod_desc',        /* field 3                  */
            'prod_id',          /* where                    */
            '=',                /* operator                 */
            $prodid         /* comparison               */
        );
        $rs = getProdDetails2SaveInInvoice($data);

Unfortunately, this doesn't work and returns the error,

ERROR:"Call to a member function execute() on a non-object".

I can confirm that the $dbh database connection is working as it's the same connection working for the inserts and updates.

  • 写回答

1条回答 默认 最新

  • doujumiao5024 2012-12-05 13:23
    关注

    You can't bind the field names. Assuming DBKEY is a constant, your query should look like this:

    $sth=$dbh->prepare("
            SELECT
                AES_DECRYPT(alt_id, ?),
                AES_DECRYPT(prod_name, ?),
                AES_DECRYPT(prod_desc, ?)
             FROM
                products
            WHERE
                prod_id = ?
        ");
    

    and $data like this:

    $data = array(
                DBKEY, 
                DBKEY, 
                DBKEY,
                $prodid
            );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?