简体   繁体   中英

How do I get the column name of a foreign key reference in PHP

I have got two tables: category and quiz

In category I have : category_id | category_name |

In quiz I have : quiz_id | quiz_name | quiz_category_id| quiz_duration

As you can notice, quiz_category_id is a FOREIGN KEY reference.

This is the code I have so far:

<table>
   <thread>
      <tr>
         <th>quiz name</th>
         <th>quiz category</th>
         <th>quiz duration</th>
     </tr>
   </thread>
     <tbody>
        <?php foreach (get_all_exam() as $r) { ?>
         <tr>
             <td><?php echo $r['quiz_name'] ?></td>
             <td><?php echo $r['quiz_category_id'] ?></td> // I am getting the id value not the name
             <td><?php echo $r['quiz_duration'] ?></td>
        </tr>
        <?php } ?>
     </tbody>
</table>

get_all_exam() is a function and here it is: This is where I do the sql query

function get_all_exam () {
    $data = array();

    $result = mysql_query("SELECT * FROM `quiz`");

    while ($row = mysql_fetch_assoc($result)) {
        $data [] = $row;
    }

    return $data;
} 

So at the minute, it just prints out for example;

| quiz name | | quiz category | | quiz duration |

|practice ex | |23| |5 minutes|

Instead of it saying 23 I want it so that it looks up on the corresponding table to get the name

Thanks

SELECT quiz.quiz_name, category.catagory_name, quiz.quiz_duration 
FROM quiz LEFT JOIN category 
ON (quiz.quiz_category_id = category.category_id)

Inside select statement, select what you want, you could also say SELECT quiz.*, category.* , but be careful if you have same field names, you might want to retrieve some with AS .

LEFT JOIN means - always show from left table, even if there is no value in the right table; thus, it will show quiz_id, even if there is no corresponding category_id. RIGHT JOIN will do just the opposite.

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