mysqli连接两个表以匹配用户名和相应的用户ID

时间:2015-01-18 06:44:07

标签: php mysqli inner-join

我很难搞清楚这一点......

我有两个表“teacher_info”和“section_info”。

在我的表单中,我包含了section_info表中的所有属性,除了我使用教师姓名而不是教师ID以便于选择,这是教师姓名的下拉列表,这是我的代码

<?php
include("anhsis.php");
mysqli_select_db($con,"anhsis");
$result= mysqli_query($con,"SELECT t_lname,t_fname FROM teacher_info");
echo"<select name='adviser' class='form-control' required>";
echo"<option value='0'>--Select Adviser--</option>";
while ($row=mysqli_fetch_array($result)) {
echo "<option value='".$row['t_lname']."".$row['t_fname']."'>".$row['t_lname'].", ".$row['t_fname']."</option>";
}
echo'</select>'
?>         

并且我的php代码在“section_info”中插入数据

<?php
        include_once('anhsis.php');
        $room_id = $_POST['room_id'];
        $section = $_POST['section'];
        $adviser = $_POST['teacher_id'];
        $level = $_POST['level'];
        $curriculum = $_POST['curriculum'];

mysqli_select_db($con,"anhsis");
    $result= mysqli_query($con,"SELECT * FROM section_info WHERE room_id= '$room_id'");
    if (mysqli_num_rows($result)>0){
        echo '<script type="text/javascript">';
        echo 'alert("TIN No already exist!")';
        echo '</script>';
    }
else{

    mysqli_query($con,"INSERT INTO section_info VALUES('$room_id','$section','$adviser','$level','$curriculum')");
    }
?> 

我的问题是在我的section_info中没有教师姓名的属性,而是有teacher_id。那么我如何通过在下拉列表中选择教师姓名,将“teacher_info”表中的teacher_id插入“section_info”表。或者有可能吗? 谢谢!

1 个答案:

答案 0 :(得分:0)

$result= mysqli_query($con,"SELECT t_lname,t_fname,teacher_id FROM teacher_info");

echo "<select name='adviser' class='form-control' required>";
echo "<option value='0'>--Select Adviser--</option>";
while ($row=mysqli_fetch_array($result)) {
    echo "<option value='".$row['teacher_id']."'>".$row['t_lname'].", ".$row['t_fname']."</option>";
}

这样,teacher_id变量中的$adviser值就可以使用了。