将变量作为查询传递时,pdo查询不执行

时间:2013-07-16 16:09:12

标签: php mysql pdo executequery

我有一个像这个$sql = $pdoObj->execute($query)的pdo命令,但它不起作用,0结果返回。我在调用$query之前回显了execute()变量,然后将其粘贴到execute()内并且代码成功运行。我无法理解这里的问题是因为我在代码的其他部分中没有遇到任何问题。 以下是一些查询示例:

SELECT s.id, s.marca, s.colore, s.prezzo, i.id_scarpa, i.taglia FROM scarpe AS s INNER JOIN info_scarpe AS i ON i.id_scarpa = s.id WHERE 1 = 1 AND taglia IN ('40','41','42') AND colore IN ('rosso', 'nero')

SELECT * FROM scarpe WHERE 1=1

SELECT * FROM scarpe WHERE 1=1 AND marca IN ('adidas','nike')

它们都是基于$_GET变量生成的动态查询。

编辑: 确定

if ( isset($_GET) ) {

                if ( isset($_GET['taglia']) ) {

                    $query = "
                            SELECT 
                                s.id, s.marca, s.colore, s.prezzo, i.id_scarpa, i.taglia
                            FROM 
                                scarpe AS s
                            INNER JOIN
                                info_scarpe AS i
                            ON i.id_scarpa = s.id
                            WHERE
                                1 = 1
                    ";
                    foreach ( $_GET as $index => $val ) {
                        $a = explode(',', $val);
                        $in =  "'" . implode("','",  $a) . "'";
                        $query .= ' AND '.$index.' IN ('.$in.')';
                    }
                } else {
                    $query = " SELECT * FROM scarpe WHERE 1=1";
                    foreach ( $_GET as $index => $val ) {
                        $a = explode(',', $val);
                        $in =  "'" . implode("','",  $a) . "'";
                        $query .= ' AND '.$index.' IN ('.$in.')';
                    }
                }
                echo 'data loaded';
            } else {
                $query = " SELECT * FROM scarpe ORDER BY id DESC ";
            }

EDIT2:

我使用的是query()而不是execute(),但仍无效

1 个答案:

答案 0 :(得分:0)

execute的参数应该是带有查询参数的数组。你的意思是使用

$result = $pdoObj->query($query);

OR

$stmt = $pdoObj->prepare($query);
$stmt->execute();