简体   繁体   中英

How to display the result from mysql union query

I have a problem displaying the result from the following query:

$sql="SELECT CONCAT(threadID,'',memberID),'posts' as Type 
      from posts 
      where memberID=$userid 
      UNION 
      SELECT CONCAT(threadID,'',memberID),'replies',as Type 
      from replies 
      where memberID=$userid order by 1";

$result=mysqli_query($con,$sql);

while($row=mysqli_fetch_array($result)){ 
    $postid=$row['thread'];
    echo $postid; 
}

The error I get is

undefined index threadID" $postid=$row['threadID'];

The problem is you don't have a column called "thread" in the output of your query...you aren't outputting that column, instead you're outputting the result of the CONCAT function.

If you write var_dump($row); as a debugging step inside your loop you would see what the row actually looks like.

A simple way to fix this is to give the calculated column an alias, so that it gets a sensible name in the $row variable. You can do this with the AS keyword in SQL. If you just call the alias "thread" then you won't have to change your PHP code at all:

SELECT CONCAT(threadID,'',memberID) AS thread,'posts' as Type 
from posts 
where memberID=$userid 
UNION 
SELECT CONCAT(threadID,'',memberID) AS thread,'replies',as Type 
from replies 
where memberID=$userid order by 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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