我正在尝试使用准备和执行函数将以下MYSQL
查询转换为PDO
语句,但因为我是PDO
的新用户,我不知道如何转换它到PDO
声明!有什么想法吗?
$db = new PDO('mysql:dbname=MYDBNAME;host=MYHOST', 'USERNAME', 'PASSWORD');
$searchName = $db->quote($_GET["searchstr"]);
$searchTerms = explode(' ', $searchName);
$searchTermBits = array();
foreach ($searchTerms as $term)
{
$term = trim($term);
if (!empty($term))
$searchTermBits[] = "f_name LIKE '%$term%' OR l_name LIKE '%$term%'";
else
$searchTermBits[] = "f_name = '$term'";
}
$mysqlResult = $db->query("SELECT * FROM food_tbl WHERE (" . implode(' OR ', $searchTermBits) . ") AND country_id = 1 ORDER BY id DESC;");
答案 0 :(得分:2)
// sanitize and build the searchTerms from the incoming `searchstr`
$searchTerms = !empty($_GET['searchstr'])
? explode(' ', $_GET['searchTerms'])
: array();
// setup a dynamic list of arguments being passed in
$where = array();
$params = array();
foreach ($searchTerms as $term) {
$term = trim($term);
if (!empty($term){
$where[] = 'l_name LIKE ?';
$params[] = $term;
}
$where[] = 'f_name ' . (empty($term) ? '=' : 'LIKE') . ' ?';
$params[] = $term;
}
// establish a new PDO object
$db = new PDO('...');
// prepare your query statement using the "static" query and a compiled
// query built from the above loop.
$query = $db->prepare('SELECT * '
. 'FROM food_tbl '
. 'WHERE country_id = 1 '
. ' AND (' . implode(' OR ', $where) . ') '
. 'ORDER BY id DESC');
// pass in the list of parameters from the above loop to the prepared
// statement and return the result
$result = $query->execute($params);
/* Work with $result */
您可以将$where
和$params
动态填充为1:1参数值列表,然后从$where
列表构建查询并传入匹配的{{1列表。
我建议将实际查询保存到变量中,然后再将其传递给$params
和$db->prepare()
/ echo
(以及var_dump
),这样您就可以看到被移交给PDO。有时候一张图片值1000字,可视化它使它有点像黑盒子,更容易理解。