2017-05-05 25 views
1

我想根据按下的字母按钮列出商店名称。 例如,如果我按'A'按钮,它应该列出从字母A开始的商店名称。我知道我应该使用LIKE查询。但是,无论如何,它使它更简单?或者一个可以使用php轻松处理的单个查询。根据所选字母按钮列出商店名称

HTML

<button class="btn btn-default">All stores</button> 
<button class="btn btn-default">A</button> 
<button class="btn btn-default">B</button> 
<button class="btn btn-default">C</button> 
<button class="btn btn-default">D</button> 

回答

0

我将每个商店的第一个字母映射到一个号码,则该号码存储为一个阵列的密钥。然后,您只需根据用户选择提供该数组的子集。

  • A - > 1
  • 乙 - > 2
  • Ç - > 3
  • ...

那么,如果有人选择B,你会回到你的2列表。所以在Mysql中它可能看起来像这样

其中MapStoreValue> = 2;

或者如果加载的所有值在数组中的PHP例如,你可以做做这样的事情:

// if your $stores array looks like this 
$stores = array(
    1 => 'A', 
    2 => 'B', 
    3 => 'C', 
    4 => 'D' 
); 

,那么你可以简单地返回该数组的所需的子集。

var_dump(array_slice($stores, 1)); 

// this returns: [2 => B, 3 => C, 4 => D] 
+0

而如果我使用IfElse这样做呢?它会方便吗? – tabia

+1

我不会使用,如果否则,这意味着你需要有一个if else块为每个案件。我会用你可以使用的一些代码更新我的答案 – lloiacono

0

我知道你说你不想使用MySQL,但在这里是对别人的解决方案,然后(未测试):

<?php 

/* Connect to a MySQL database using driver invocation */ 
$dsn = 'mysql:dbname=testdb;host=127.0.0.1'; 
$user = 'dbuser'; 
$password = 'dbpass'; 

// Try to create a connection 
try { 
    $dbh = new PDO($dsn, $user, $password); 
} catch (PDOException $e) { 
    echo 'Connection failed: ' . $e->getMessage(); 
} 

// Query 
$sql = 'SELECT * FROM table '; 

// Get the letter selected 
$letter = isset($_POST['letter']) ? $_POST['letter'] : ''; 

// If letter is not empty 
if(!empty($letter)){ 
    // Query continued 
    $sql .= 'WHERE store_name LIKE :letter'; 
} 

// The prepared statement 
$sth = $dbh->prepare($sql); 

// Binding the value of the $letter to the query 
if(!empty($letter)){ 
    $sth->bindValue('letter', "$leẗter%"); 
} 

// Executing the query 
$sth->execute(); 

// Fetching the results 
$stores = $sth->fetchAll(PDO::FETCT_OBJ);