我创建了这个函数:
<?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
[编辑]看起来它只添加了第二个参数。如果我更改OR
它AND
仍然会给出一个结果,即使它根本不应该给出任何行(因为不能有 ID = 2 AND ID = 8 选项)。
[EDIT2]我设置了查询日志并得到了我的想法。实际查询是SELECT * FROM list WHERE id='8' OR id='8' ORDER BY id DESC