MySQLi从两个表中选择限制

时间:2014-12-24 09:32:56

标签: php mysql mysqli

我一直尝试将mysql数据库中的两个表组合在一起,两个表status and status_reply都有相同的列号和名称,即id, account_name, author, postdate, data请帮助我们

            $limit = "LIMIT 0, 10";
        $query = mysqli_query($db_conx, "(SELECT * `status` as type from status WHERE data LIKE '%".$tag."%' ORDER BY postdate DESC $limit)
                                    UNION (SELECT * `status_reply` as type from status_reply WHERE data LIKE '%".$tag."%' ORDER BY postdate DESC $limit)");

            //$query = mysqli_query($db_conx, "SELECT * FROM status WHERE data LIKE '%$tag%' ORDER BY postdate DESC $limit");
            $statusnumrows = mysqli_num_rows($query);
            while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
            $statusid = $row["id"];
            $account_name = $row["account_name"];
            $author = $row["author"];
            $postdate = $row["postdate"];
            $data = $row["data"];
            $data = nl2br($data);
            $data = str_replace("&","&",$data);
            $data = stripslashes($data);
            $statuslist .= '<div id="status_'.$statusid.'" class="status_boxes"><div><b>Ivotised by <a href="home.php?u='.$author.'">'.$author.'</a> '.$postdate.':</b>
<article>'.$data.'</article>
</div></div>';
            }

2 个答案:

答案 0 :(得分:1)

  1. 对字段名称使用反引号`而不是直接引用&#39;
  2. 请勿忘记引用$tag以防止SQL注入:mysqli_real_escape_string
  3. 请记住,那就是你想要字面搜索LIKE通配符&#34;%&#34;,&#34; _&#34;以及反斜杠。你需要使用:$tag = addcslashes($tag, '\%_');
  4. 来逃避它们
    $limit = "LIMIT 0, 10";
    $query = mysqli_query($db_conx, "
    (SELECT `status` as type from status WHERE data LIKE '%".$tag."%' 
         ORDER BY postdate DESC $limit)
    UNION 
    (SELECT `status_reply` as type from status_reply WHERE data LIKE '%".$tag."%' 
         ORDER BY postdate DESC $limit)");
    

答案 1 :(得分:0)

我意识到我必须删除status和status_reply中的类型作为对表的引用,并按名称标识每个列。我也很好奇!

$query = mysqli_query($db_conx, "
(SELECT id, account_name, author, postdate, data from status WHERE data LIKE '%".$tag."%' 
     ORDER BY postdate DESC $limit)
UNION 
(SELECT id, account_name, author, postdate, data from status_reply WHERE data LIKE '%".$tag."%' 
     ORDER BY postdate DESC $limit)");
相关问题