Mysql SELECT WHERE id =? AND url = 1,0或全部

时间:2016-09-30 04:31:08

标签: php mysql

我有一个显示消息的系统,但用户可以选择查看正(1)和消极(0)消息,但也有一个链接,您可以看到所有消息(1和0),我可以做这个查询?

的index.php ID = 1&安培;?URL = 1

strselect

我可以更改单词&#34; <?php function mesage($id, $url) { $db = DB::getInstance(); $query = $db->query("SELECT * FROM mesage WHERE id = ? AND url = ?", array($id, $url)); $results = $query->results(); return ($results); } $url = isset($_GET["url"])?$_GET["url"]:'Select 0 and 1'; $id = $_GET['id']; $getmesaje = mesage($id, $url); ?> &#34;在变量&#34; Select 0 and 1&#34;显示所有?

2 个答案:

答案 0 :(得分:1)

您可以使用

index.php?id = 1&amp; url = 1 // for positive

index.php?id = 1&amp; url = 0 //表示否定

index.php?id = 1 //适用于所有

<?php 
function mesage($id, $url) {
    $db = DB::getInstance();
    if(empty($url)) {
        $query = $db->query("SELECT * FROM mesage WHERE id = ?",$id);
    } else {
        $query = $db->query("SELECT * FROM mesage WHERE id = ? AND url = ?", array($id, $url));
    }
    $results = $query->results();
    return ($results);
}

$url = isset($_GET["url"])?$_GET["url"]:'';
$id = $_GET['id'];
$getmesaje = mesage($id, $url);
?>

答案 1 :(得分:1)

准备动态查询取决于用户输入。并在where子句中使用IN

<?php 
        function mesage($id, $url) {

         $concatenate='';

         if(!empty($url))
         {

             $concatenate.= "  AND url IN(?)";

             $param = array($id, $url);
         }
         else
         {
            $param = array($id);

         }

        $db = DB::getInstance();
        $query = $db->query("SELECT * FROM mesage WHERE id = ? $concatenate ",$param );
        $results = $query->results();
        return ($results);
        }

        $url = isset($_GET["url"])?$_GET["url"]:'';
        $id = $_GET['id'];

        if(!empty($id))
        {
           $getmesaje = mesage($id, $url);
        }
    ?>

更新1: 根据评论你的正确当$ url带有0值时,它认为是空的。所以应该if(strlen($url)>0){}这样。

<?php 
    function mesage($id, $url) {

     $concatenate='';

     if(strlen($id)>0)
     {

         $concatenate.= "  AND url IN(?)";

         $param = array($id, $url);
     }
     else
     {
        $param = array($id);

     }

    $db = DB::getInstance();
    $query = $db->query("SELECT * FROM mesage WHERE id = ? $concatenate ",$param );
    $results = $query->results();
    return ($results);
    }

    $url = isset($_GET["url"])?$_GET["url"]:'';
    $id = $_GET['id'];

    if(strlen($id)>0)
    {
       $getmesaje = mesage($id, $url);
    }
?>