我不知道这只是PDO连接到MDB ACCESS数据库(而不是MySQL)的问题,但是我在使用预准备语句插入%
的所有SELECT查询中都有问题。
这是我的例子:
Table.Col1 is a TEXT field
Table.Col2 is a INT field
当我在Col1
内搜索时,我想搜索确切的字词(不是以......开头,或以......结尾但是我通过的确切字词)
编译表的示例
| ID | Col1 | Col2 |
-------------------------
| 1 | test | 23 |
-------------------------
| 2 | apple | 24 |
-------------------------
| 3 | applejuice| 33 |
-------------------------
| 4 | yellow | 76 |
-------------------------
| 5 | brown | 50 |
-------------------------
<?php
$dbName = "Database.mdb";
try{
$db= new PDO("odbc:DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=$dbName; Uid=; Pwd=;");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
echo $e->getMessage();
exit();
}
function test($filters = array()) {
$sql = "SELECT * FROM Table WHERE 1";
$vars = array();
// FILTER BY Col1
if ( isset($filters['Col1']) && $filters['Col1'] != "" ) {
$sql .= " AND [Table].[Col1] LIKE ?";
$vars[] = $filters['Col1'];
}
// FILTER BY Col2
if ( isset($filters['Col2']) && $filters['Col2'] != "" ) {
$sql .= " AND [Table].[Col2] = ?";
$vars[] = $filters['Col2'];
}
try {
$s = $db->prepare($sql);
$s->execute($vars);
$ris = $s->fetchAll(PDO::FETCH_ASSOC);
return $ris;
} catch (PDOException $e) {
die($e);
}
}
现在这是我的测试:
var_dump(test(array("Col1" => "test")));
// OUTPUT CORRECT
array(
0 => array(
"ID" => 1,
"Col1" => test,
"Col2" => 23
)
);
var_dump(test(array("Col1" => "apple")));
// OUTPUT CORRECT
array(
0 => array(
"ID" => 2,
"Col1" => applejuice,
"Col2" => 33
)
);
var_dump(test(array("Col1" => "%")));
// OUTPUT INCORRECT !!!!
// I GET ALL TABLE!!! I WANT TO RETRIEVE A EMPTY RESULT ARRAY
array(
0 => array(
"ID" => 1,
"Col1" => test,
"Col2" => 23
),
1 => array(
"ID" => 2,
"Col1" => apple,
"Col2" => 24
),
2 => array(
"ID" => 3,
"Col1" => applejuice,
"Col2" => 33
),
3 => array(
"ID" => 4,
"Col1" => yellow,
"Col2" => 76
),
4 => array(
"ID" => 5,
"Col1" => brown,
"Col2" => 50
),
0 => array(
"ID" => 2,
"Col1" => applejuice,
"Col2" => 33
)
);
为什么准备好的声明不起作用?我有很多功能,我需要在哪里搜索一个完整的测试...我如何用%
为我的所有表解决这个问题而不重写我的所有功能(我的功能超过100个)项目!!!)?