重构字母通配符

时间:2014-07-10 15:25:25

标签: php mysql pdo

如何重构这个以处理每个字母(a到z)我不想为每个字母重写查询。

显示HTML:

<div class="questionWrapper">
  <div class="question">
    <h3>A</h3>
    <?php foreach ($categoryA as $category) : ?>
       <p class="view"><?= $category['category']; ?></p>
    <?php endforeach; ?>
  </div>
</div>

查询示例:

$categoryA = query('SELECT * FROM category WHERE category LIKE "A%"',
  array('category' => ['category']),
  $conn);

$categoryB = query('SELECT * FROM category WHERE category LIKE "B%"',
  array('category' => ['category']),
  $conn);

功能:

function query($query, $bindings, $conn)
{
    $stmt = $conn->prepare($query);
    $stmt->execute($bindings);
    return $stmt;
}

1 个答案:

答案 0 :(得分:0)

我修复了你使用占位符:

$category = query('SELECT * FROM category WHERE category LIKE :category',
  array(':category' => '%'.$letter.'%'),
  $conn);