繁体   English   中英

动态创建mysql选择查询

[英]Dynamically Creating mysql select Query

我的网站中有多个复选框:复选框1复选框2复选框3等。

我想基于上面的复选框动态生成mysql查询。

i:e如果选择第一个复选框,则查询应为:

$mysql="Select * from mytable where colname=" . $checkbox1 .;

如果选中第一个和第二个复选框,则查询应为:

$mysql="Select * from mytable where colname=" . $checkbox1 ."AND colname=" . $checkbox2 ." ;

如果所有都被选中那么它应该是:

$mysql="Select * from mytable where colname=" . $checkbox1 . "AND colname=" . $checkbox2 ."AND colname=" . $checkbox3 .  ;

有人可以帮忙:

你必须改变你的形式,因为它取多个值,它应该作为一个数组发布

<form action="register.php" method="POST"> 
  <input type="checkbox" name="rating[]" value="5">5 Star 
  <input type="checkbox" name="rating[]" value="4">4 Star 
  <input type="checkbox" name="rating[]" value="3">3 Star 
  <input type="checkbox" name="rating[]" value="2">2 Star 
  <input type="checkbox" name="rating[]" value="1">Less than 2 Star 
</form>

然后在PHP中

  $where = '';
   if(isset($_POST['rating'])){
     $data = implode(',',$_POST['rating']); // beacuse your rating is only one column in db i think
     $where = "WHERE cloumn_name IN($data)";
   }
  $query = "SELECT * FROM your_table $where";

您可以使用字符串连接和一些技巧来完成工作。 不要依赖于isset,而是使用!empty。

<form action="example.php" method="post">
    <input type="checkbox" name="Col1" value="colname" />Col 1</br>
    <input type="checkbox" name="Col2" value="colname" />Col 2</br>
    <input type="checkbox" name="Col3" value="colname" />Col 3</br>
</form>
<?php
if(!empty($_POST)) {
    $string = '';
    if(!empty($_POST['col1'])) {

        $string.= "column1 ='".$_POST['col1']."'";
    }   
    if(!empty($_POST['col2'])){

        if(!empty($string)) {

            $string.=" AND ";

        } 
        $string.= "column2 ='".$_POST['col2']."'";

    }
    if(!empty($_POST['col3'])){
        if(!empty($string)) {

            $string.=" AND ";

        } 

        $string .= "column3 ='".$_POST['col3']."'";
    }

    if(!empty($string)) 
    {
        //execute your query here.
    }
}

关于它的一些事情

<? if ($_POST[option]==1) { 
      //query 
   } 
?>

<form method="post">
   <input type="checkbox" name="option" value="1">1
   <input type="checkbox" name="option" value="2">2
   <input type="checkbox" name="option" value="3">3
</form>

只需检查你的复选框是否被选中(isset($ _ POST [checkbox1]))

所以你可以做点什么

if (isset($_POST[checkbox1])
{
//statement
}
else if (isset($_POST[checkbox2])
{
//statement2...
}
...

在这里阅读更多

干杯

从下面提供的代码中可以明显看出,我当然不是PHP编码器。 但无论如何,这是一个思考的想法......

尝试使用0到127之间的input不同值,例如?input=66

<?php

if(isset($_GET['input'])){

   $input = $_GET['input'];

   }else{

   $input=0;
}

$days = array('mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun');

for( $i=0; $i<7; $i++ ) {
    $daybit = pow(2,$i);
    if( $input & $daybit ) {
        echo "<input type = checkbox checked/>$days[$i]";
    }else{
        echo "<input type = checkbox>$days[$i]";
}
}
?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM