我正在处理用户的自定义报告。在此页面中,我为数据库中的选择数据提供了一个用户复选框选项。用户可以选择他想要从表中查看的数据。我的表有很多字段,如名称,阻止,联系..等等。如果用户只想看到uid和名字,那么他只会检查姓名和电话的方框。 我的复选框是
<form action="#" method="post">
<input type="checkbox" name="check_list[]" value="uid"><label>uid</label>
<input type="checkbox" name="check_list[]" value="name"><label>name</label>
<input type="checkbox" name="check_list[]" value="block"><label>block</label>....and so more
<input type="submit" name="submit" value="Submit"/>
</form>
和我正在尝试的PHP代码是
if(isset($_POST['submit'])){
$sql[] = "select ";
foreach($_POST['check_list'] as $selected){
$sql[]=$selected.',';
}
$sql[]= " from emitra_basic LIMIT 5";
foreach ($sql as $user) {
$ram="$user";
}
if ($result=mysqli_query($conn, $ram))
{
while ($row=mysqli_fetch_row($result))
{
echo "id".$row['uid']."<br/>";
echo "name".$row['name']."<br/>";
}
}
}
但没有结果。我该怎么办?
答案 0 :(得分:0)
请尝试
$sql[] = "select ".implode(', ', $_POST['check_list'])." from emitra_basic LIMIT 5";
而不是
$sql[] = "select ";
foreach($_POST['check_list'] as $selected){
$sql[]=$selected.',';}
$sql[]= " from emitra_basic LIMIT 5";
得到类似的东西:
select uid, name, block from emitra_basic LIMIT 5;
否则在最后一个字段的末尾会有一个,
:
select uid, name, block, from emitra_basic LIMIT 5; -- This is not working!
答案 1 :(得分:0)
尝试这样: - 编码没有大的改变
if(isset($_POST['submit'])){
$sql=array();
$sql[] = "select ";
$sql[]=join(",", $_POST['check_list']);
$sql[]= " from emitra_basic LIMIT 5";
//print_r($sql);
foreach ($sql as $user) {
//echo $user."<br>";
$ram.=$user;
}
//echo $ram; exit;
//select uid, from emitra_basic LIMIT 5
if ($result=mysqli_query($conn, $ram))
{
while ($row=mysqli_fetch_row($result))
{
echo "id".$row['uid']."<br/>";
echo "name".$row['name']."<br/>";
}
}
}
答案 2 :(得分:0)
在php中尝试这个
if(isset($_POST['submit'])){
$sql1 = "select ";
$sql2 = "";
$checklist = $_POST['check_list'];
$count = count($checklist);
if($count!=1){
$count = $count-1;
for ($i=0; $i < $count ; $i++) {
$sql2 = $sql2.$checklist[$i].",";
}
$sql2 = $sql2.$checklist[$count];
} else{
$sql2 = $checklist[0];
}
$sql3= " from emitra_basic LIMIT 5";
$totalSql = $sql1.$sql2.$sql3;
if ($result=mysqli_query($conn,$totalSql))
{ while ($row=mysqli_fetch_row($result))
{ echo "id".$row['uid']."<br/>";
echo "name".$row['name']."<br/>";}}
}