我从这里使用 ajax livesearch:Ajax Livesearch
我想让用户在数据库中搜索城市,到目前为止它工作得很好。当我输入字母时,它会显示城市和邮政编码。现在我尝试使用密码使相同的搜索框也可以工作,这样如果用户按邮政编码搜索,城市就会显示出来。但我完全被困住了。也许有人对搜索框有一些经验,可以帮助我。
在config.php
我定义的搜索列中:
const USER_TABLE = 'cities';
const SEARCH_COLUMN = 'Name';
要从数据库中获取结果,我有这个:
$db = DB::getConnection();
// get the number of total result
$stmt = $db->prepare('SELECT COUNT(id) FROM ' . Config::USER_TABLE . ' WHERE ' . Config::SEARCH_COLUMN . ' LIKE :query');
$search_query = $query.'%';
$stmt->bindParam(':query', $search_query, PDO::PARAM_STR);
$stmt->execute();
$number_of_result = $stmt->fetch(PDO::FETCH_COLUMN);
// initialize variables
$HTML = '';
$number_of_pages = 1;
if ( (int) $number_of_result !== 0)
{
if ($items_per_page === 0)
{
// show all
$stmt = $db->prepare('SELECT * FROM ' . Config::USER_TABLE . ' WHERE ' . Config::SEARCH_COLUMN . ' LIKE :query ORDER BY ' .Config::SEARCH_COLUMN);
$search_query = $query.'%';
$stmt->bindParam(':query', $search_query, PDO::PARAM_STR);
}
else
{
/*
* pagination
*
* calculate total pages
*/
if ($number_of_result < $items_per_page)
$number_of_pages = 1;
elseif ($number_of_result > $items_per_page)
$number_of_pages = floor($number_of_result / $items_per_page) + 1;
else
$number_of_pages = $number_of_result / $items_per_page;
/*
* pagination
*
* calculate start
*/
$start = ($current_page > 0 ) ? ($current_page - 1) * $items_per_page : 0;
$stmt = $db->prepare('SELECT * FROM ' . Config::USER_TABLE . ' WHERE ' . Config::SEARCH_COLUMN . ' LIKE :query ORDER BY '.Config::SEARCH_COLUMN.' LIMIT ' . $start . ', ' . $items_per_page);
$search_query = $query.'%';
$stmt->bindParam(':query', $search_query, PDO::PARAM_STR);
}
// run the query and get the result
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
这将在我的网站上显示结果:
foreach($results as $result)
{
$HTML .= "<tr><td>{$result['Name']}</td><td>{$result['Postal_Code']}</td></tr>";
}
因此,如果我输入字母,它还会从“Postal_Code”列中为我提供正确的邮政编码。但我想也可以用另一种方式来做,我输入数字,它会显示城市和邮编?在config.php
i 中只能定义一列
const SEARCH_COLUMN = 'Name';
也许可以使用第二个常量,例如:
const SEARCH_COLUMN2 = 'Postal_Code';
? 但是我怎样才能在 db 查询中使用它呢?解释我的问题对我来说有点困难,所以我希望你能以任何方式理解我:) 谢谢