2

I am trying to use a result from one query as input for another query but I am stumped. I thought about using JOIN but I think in this case the two queries need to me run separately. Essentially I have a list of articles in my database. As I loop through the list or articles that I obtained from my first query I want to search a second table to find out the number of votes that each article has.

This is the code:

<?php
  $sql=mysql_query("SELECT * FROM discussion_links WHERE link_side = 'Michigan'");
  while($row = mysql_fetch_array($sql)) {
?>

<div class="top-links-wrapper">
    <div>
       <div class="link-info">
           <a class="link-title" href="http://<?php echo $row['link_url'] ?>">
           <?php echo $row['link_title'] . "</a>"; ?>
           <p class="link-source"><?php echo $row['link_source'] . "</p>" ?>
       </div>
       <div class="link-vote-wrapper">
           <span class="link-votes">
           <?php    
                $sql2=mysql_query("SELECT * FROM link_votes WHERE link_id = " . $row['link_id'] .")";
                $num_rows = mysql_num_rows($sql2);
                echo "$num_rows";
            ?>
           </span>
       </div>
    </div>
</div>

Thanks

2

3 Answers 3

7

You can join both queries try this

SELECT dl.* , lv.*
FROM discussion_links dl
LEFT JOIN link_votes lv ON lv.link_id = dl.link_id
WHERE link_side = 'Michigan'
Sign up to request clarification or add additional context in comments.

Comments

1

Change

$sql2=mysql_query("SELECT * FROM link_votes WHERE link_id = " . $row['link_id'] .")";

to

$sql2=mysql_query("SELECT * FROM link_votes WHERE link_id = " . $row['link_id']);

The closing bracket ) is part of the function call not the query

or better would be to create a single query :

SELECT * FROM discussion_links d 
JOIN link_votes v
on d.link_id = v.link_id
WHERE d.link_side = 'Michigan'

You should replace the SELECT * and just select the columns you require

2 Comments

Thanks, just noticed the error with the ')'. Will try that 2nd query you suggest.
@LuisP you may need to do a left join as there may be articles that have no votes
0

Fixed, had an error in the 2nd query:

$sql2=mysql_query("SELECT * FROM link_votes WHERE link_id = " . $row['link_id']);

It now works.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.