dongwang6837
2015-10-03 14:34
浏览 137

MySql:在子查询中引用父查询fetched数组

I am trying to refer the parent query fetched array in sub query of same statement. I have a news table and I want to get a specific news by its title and 10 more news which have id lower than that specific news. I want in one statement of Sql and i am php to fetch array.

<?php
// $_GET['q'] is title
include('db.php');
$result = array();
$sel = "SELECT * FROM news WHERE title = '".$_GET['q']."' ";  // AND 10 MORE NEWS WHICH HAVE ID LOWER THAN THIS  $_GET['q'] ID .
$qry = @mysqli_query($conn , $sel);
$num = mysqli_num_rows($qry);
while($row = @mysqli_fetch_array($qry)) {
array_push($result, array('id' => $row['id'] , 'title' => $row['title'] ,  'desc' => $row['about'] , 'image' => $row['image'] , 'time' => $time , 'htitle'  => $row['Htitle'] , 'habout' => $row['Habout']));
}
echo json_encode(array('result' => $result));
?>

图片转代码服务由CSDN问答提供 功能建议

我试图在同一语句的子查询中引用父查询fetched数组。 我有一个新闻表,我希望通过其标题获得一个特定的新闻和另外10个新闻,这些新闻的ID低于特定新闻。 我想在一个Sql语句中,我是php来获取数组。

 &lt;?php 
 // $ _GET ['q']是title 
include('  db.php'); 
 $ result = array(); 
 $ sel =“SELECT * FROM news WHERE title ='”。$ _ GET ['q']。“'”;  //还有10个新ID,其ID低于$ _GET ['q'] ID。
 $ qry = @mysqli_query($ conn,$ sel); 
 $ num = mysqli_num_rows($ qry); 
while(  $ row = @mysqli_fetch_array($ qry)){
array_push($ result,array('id'=&gt; $ row ['id'],'title'=&gt; $ row ['title'],'desc'  =&gt; $ row ['about'],'image'=&gt; $ row ['image'],'time'=&gt; $ time,'htitle'=&gt; $ row ['Htitle'],'habout  '=&gt; $ row ['Habout'])); 
} 
echo json_encode(array('result'=&gt; $ result)); 
?&gt; 
   \  n 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dpfwhb7470 2015-10-03 16:02
    已采纳

    Your original query is SELECT * FROM news WHERE title = :title.

    If you really want to use a subquery use something along the lines of

    SELECT 
      * 
    FROM news 
    WHERE id < 
      (SELECT 
        id 
      FROM news 
      WHERE title = :title
      LIMIT 1) 
    ORDER BY id DESC 
    LIMIT 10
    

    A final note: PLEASE use parameters in your query, because you are WIDE OPEN to SQL injection (think about when $_GET['q'] has a value of ; DROP TABLE news;--).

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题