我正在编写一个查询,从数据库中获取一个ID,其最后一位数可以是1-5。这有效,但看起来很混乱。有没有更简洁的方法呢?
$id1 = $id.'1';
$id2 = $id.'2';
$id3 = $id.'3';
$id4 = $id.'4';
$id5 = $id.'5';
$sql = "SELECT col1
FROM table1
WHERE id = :id1 OR id = :id2 OR id = :id3 OR id = :id4 OR id = :id5
LIMIT 1";
$core = Connect::getInstance();
$stmt = $core->dbh->prepare($sql);
$stmt->bindParam(':id1', $id1, PDO::PARAM_STR);
$stmt->bindParam(':id2', $id2, PDO::PARAM_STR);
$stmt->bindParam(':id3', $id3, PDO::PARAM_STR);
$stmt->bindParam(':id4', $id4, PDO::PARAM_STR);
$stmt->bindParam(':id5', $id5, PDO::PARAM_STR);
$stmt->execute();
$data = $stmt->fetchAll();
答案 0 :(得分:0)
试试这个
$sql = "SELECT col1
FROM table1
WHERE id = :id1 OR id = :id2 OR id = :id3 OR id = :id4 OR id = :id5
LIMIT 1";
$core = Connect::getInstance();
$stmt = $core->dbh->prepare($sql);
for($i; $i<=5; $i++){
$stmt->bindParam(':id'.$i, $id.$i, PDO::PARAM_STR);
}
$stmt->execute();
$data = $stmt->fetchAll();
答案 1 :(得分:0)
另一种选择是使用问号占位符。所有值,只需在->execute
方法中加载所有值:
问号占位符:
$sql = "SELECT col1
FROM table1
WHERE id = ? OR id = ? OR id = ? OR id = ? OR id = ?
LIMIT 1";
内部执行:
$stmt->execute(array($id1, $id2, $id3, $id4, $id5));