我有一个表(设施),其中字段名称是swimming_pool,餐厅,WiFi,图书馆等。 如果一个特定的房子只有两个可用的设施,我给那些可用的字段名称值1,如果不是0。 我想检索值为1的所有字段名称,并使用备用名称回显值为1的每个字段。
这是我想要实现的目标
$st = $db->prepare(select * from facility where house_id = ?);
$st->execute(array($_GET['house_id']));
$row = $st->fetch();
从上面我必须选择值为1的所有字段。对于所有那些值为1的字段,我必须回显名称(例如:如果swimming_pool值为1,我必须回显游泳池,如果它是0则检查下一栏)
我希望你明白我的目标。
答案 0 :(得分:-1)
我希望我解决了你的问题?我还没有测试它,所以如果可能有问题,请做一个评论。
<?php
/*
* Sample Link: web.com/index.php?house_id=1&search=1,0,0,1
*/
/*
* Sample Fields:
* swimming_pool, restaurant, wifi, library
*/
//Explode the $_GET['search'] to create an array
$fields_to_search = explode(",",$_GET['search']);
//Manually set the fields
$db_fields = [
'swimming_pool',
'restaurant',
'wifi',
'library'
];
$fields_to_be_selected = "";
//Create a counter as basis to store if the Link is 1 or 0, then pass it to $db_fields[]
$counter = 0;
foreach($fields_to_search as $field) {
//Check if $field is 1
if($field == 1) {
//Then pass it to $table_to_be_selected and add a COMMA
$fields_to_be_selected .= $db_fields[$counter].",";
}
$counter++;
}
//Remove the last COMMA
$fields_to_be_selected = substr($fields_to_be_selected,0,-1);
/*
* LASTLY DO THE prepare()
*/
$query = sprintf("SELECT %s FROM `facility` WHERE `house_id` = ?",$fields_to_be_selected);
$stmt = $db->prepare($query);
$stmt->execute(array($_GET['house_id']));
$rows = $stmt->fetchAll();
//It will only print the selected fields
print_r($rows);
?>