2011-09-30 63 views
2

我有一些古老的代码,我要转换为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; 
    }  
?> 
+1

你真的连接到预处理语句数据库每次运行查询时? –

+0

@Col。据我所知,弹片是的。 – oshirowanen

+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"; 

要利用你有你的值添加到数组,然后用它来与执行()

+0

+1你会不会碰巧与那些自酿的占位符有关联? – Johan

+0

那么,它最近才可用。 https://github.com/colshrapnel/safemysql如果你仍然很有趣。欢迎您使用并批评它:) –

0

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

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

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

+0

你的方式过于谨慎:)'PDO :: PARAM_INT并没有真正将你的变量转换为int' - 它做了什么? –

+0

@Col。弹片如果我没有记错,没有,但我找不到一个参考,所以我已经删除它... – jeroen

+0

好吧,它什么也没做,所以呢?后果是什么? –