-1

我正在尝试将以下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;");
4

1 回答 1

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列表构建查询并传入匹配$params列表。

我建议在将实际查询传递给$db->prepare()echo/var_dump它(连同$params)之前将其保存到变量中,这样您就可以看到传递给 PDO 的内容。有时一张图片值 1000 字,将其可视化会使它不像黑匣子,更容易理解。

于 2013-07-08T13:29:06.217 回答