【发布时间】:2012-10-03 10:04:16
【问题描述】:
我已经创建了这个函数:
<?php
$pdo_db = new PDO( 'mysql:host=' . $db_host . ';dbname=' . $db_name, $db_user_name, $db_password );
function qlist_pdo( $fields, $tables, $where_fields='', $where_values='', $order='', $limit='' ) {
GLOBAL $pdo_db; // ignore this, it will be in class later. This is just for test purposes
if ( $order ) $order = ' ORDER BY ' . $order;
if ( $limit ) $limit = ' LIMIT ' . $limit;
if ( is_array( $where_fields ) && is_array( $where_values ) && isset( $where_fields ) && isset( $where_values ) ) {
if ( sizeof( $where_fields ) != sizeof( $where_values ) ) {
die( "Query error: where <strong>field</strong> count doesn't match <strong>value</strong> count!" );
} else {
$where = ' WHERE ';
foreach( $where_fields as $key => $value ) {
$where .= $key . ' ' . $value . '=? ';
}
$where = substr( $where, 0, -1 );
echo $query = "SELECT " . $fields . " FROM " . $tables . $where . $order . $limit;
$qp = $pdo_db -> prepare( $query );
foreach ( $where_values as $key => $val ) {
$qp -> bindParam( $key+1, $val );
}
}
} else {
echo $query = "SELECT " . $fields . " FROM " . $tables . $order . $limit;
$qp = $pdo_db -> prepare( $query );
}
$qp -> execute();
$result = $qp -> fetchAll();
return $result;
}
?>
我这样称呼它:
$result = qlist_pdo( "*", "list", array( '' => 'id', 'OR' => 'id' ), array( '2', '8' ), 'id DESC' );
当我设置 where 参数时,它工作正常,但结果只有 1 行(应该是 2 )。如果我在没有像这样的参数的情况下调用它:
$result = qlist_pdo( "*", "list", '', '', 'id DESC' );
它返回所有行。为什么会这样,我做错了什么?
查询生成:
SELECT * FROM list WHERE id=? OR id=? ORDER BY id DESC
生成的参数:
1, 2
2, 8
[EDIT] 看起来它只添加了第二个参数。如果我将 OR 更改为 AND 它仍然会给出一个结果,即使它根本不应该给出任何行(因为不能有 ID = 2 AND ID = 8 选项)。
[EDIT2] 我设置了查询日志并得到了我的想法。实际查询为SELECT * FROM list WHERE id='8' OR id='8' ORDER BY id DESC
【问题讨论】:
-
查看生成的 2 个查询会有所帮助