简体   繁体   中英

PHP only display rows from a mysql table that are associated with User ID

I hope someone can help me out,

I have two tables wp_wp_pro_quiz_statistic_ref and wp_wp_pro_quiz_statistic the common link between them is statistic_ref_id .

The data a want to display is in wp_wp_pro_quiz_statistic I can fetch it using something like this:

<?php
global $wpdb;
$current_user = wp_get_current_user();
$current_user_statid = $wpdb->get_results( "SELECT * FROM wp_wp_pro_quiz_statistic_ref WHERE user_id = $current_user->ID");

$result = $wpdb->get_results( "SELECT * FROM wp_wp_pro_quiz_statistic WHERE $current_user_statid = statistic_ref_id");

echo "Question:"."  "."Points:"."<br><br>";
foreach($result as $row)
{

echo $row->question_id." ".$row->points."<br>";

}
?>

wp_wp_pro_quiz_statistic_ref stores the user_id and statistic_ref_id the user ID can be pulled using $current_user = wp_get_current_user(); or something similar. Im not sure how to then use 'statistic_ref_id' to only display rows that match the value of statistic_ref_id in wp_wp_pro_quiz_statistic .

Update:

    <table border="1" width="500px">
        <tr>
            <th>Question Number</th>
<th>Clause</th>
<th>Subject</th>
            <th>Score</th>
        </tr>
<?php
global $wpdb;
$current_user = wp_get_current_user();
$result = $wpdb->get_results( "
SELECT stats.*
  FROM wp_wp_pro_quiz_statistic stats
       JOIN wp_wp_pro_quiz_statistic_ref refs on stats.statistic_ref_id = refs.statistic_ref_id
WHERE refs.user_id= $current_user->ID ");
foreach($result as $row) {
echo "<tr>
                <td>$row->question_id</td>
<td>some clause</td>
<td>some subject</td>
                <td>$row->points</td>
            </tr>";
}
?>
</table>
<table border="1" width="500px">
<tr><td width="445px">Total Score (Maximum 125)</td><td width="55px">0</td> </tr>
</table>
</body>
</html>

If I've understood your question, you should be able to use a SQL join; something like this:

<?php
global $wpdb;
$current_user = wp_get_current_user();
$result = $wpdb->get_results( "
    SELECT stats.*
      FROM wp_wp_pro_quiz_statistic stats
           JOIN wp_wp_pro_quiz_statistic_ref refs on stats.statistic_ref_id = refs.statistic_ref_id
    WHERE refs.user_id= $current_user->ID ");

echo "Question:"."  "."Points:"."<br><br>";
foreach($result as $row) {
    echo $row->question_id." ".$row->points."<br>";
}
?>

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