简体   繁体   中英

Run a mysql query in a mysql query

Hello I'm trying to query my database table "shout_out", during the while loop I have an if statement to check to if the "convers_id" column has been change from no_reply. if it has I want another query to run and get all the rows from shout_out_reply table that have the same "convers_id" column. I'm trying to get a similar lay out as a facebook "wall". Some one make a comment and others can reply to that comment with the reply being under the original comment.

I keep getting that the mysqli_query($dbc, $query_shout_out_reply) has failed. but there are reply's with the same "convers_id"

$query_shout_out = "SELECT * FROM shout_out WHERE sent_to = '$username' ";
$shout_out_query = mysqli_query($dbc, $query_shout_out);

if (mysqli_num_rows($shout_out_query) != 0) {
    while ($row = mysqli_fetch_array($shout_out_query)) {
        echo '<td class="shout_out_display" width="550">';
        echo $row['message'] . ' <br/><br/> From ' . $row['sent_by'] . ' at ' . $row['date_sent'];
        echo '</td></tr>';
        echo $row['convers_id'];
        if ($row['convers_id'] != "no_reply") {
            $query_shout_out_reply = "SELECT * FROM shout_out_reply WHERE convers_id = " . $row['convers_id'];
            $shout_out_reply_query = mysqli_query($dbc, $query_shout_out_reply);

            while ($reply_row = mysqli_fetch_array($shout_out_reply_query)) {
                echo ' <tr width="550"><td width="125" > &nbsp </td>';
                echo '<td width="425"  class="shout_out_reply_display">';
                echo $reply_row['message'] . '<br/><br/>Reply From ' . $reply_row['sent_by'] . ' at ' . $reply_row['date_sent'];
                echo '</td></tr>';
            }
        }

    }
}
SELECT * FROM shout_out AS so LEFT JOIN shout_out_reply AS sor ON sor.convers_id = so.convers_id WHERE so.sent_to = '$username' AND so.convers_id != 'no_reply'

The key here is to use an SQL JOIN statement. It'll give you the results from both tables in one statement. ...then you don't have to go through the loop. making all those sql requests.

you mast design tables such structure, that will easy you create joins and complex querys. first of all, you need to understood how works joins and when they must use. check google for this.

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