如何在sql中选择相应的ID

问题描述 投票:0回答:1

我是php的新手,我正在尝试创建一个学校门户,现在我正在尝试创建一个页面,管理员可以在该页面上课程。我只需要知道如何做,就是允许管理员从下拉菜单中选择一位老师(名称或用户名直接来自数据库),然后在Teacher_id的“班级”表中输入相应的ID。

$query = "SELECT Username FROM tbluser WHERE Role='Teacher'";
$result2= mysqli_query($conn, $query);
<body>

            <form action="createclass.php" method="POST">
                <div>
                    <label>Class name</label>
                    <input type="text" name="classname" class="form-control" placeholder="Enter new username">
    <br/>
                    <label>Teacher</label>
                    <select name ="teacher">
                        <option  selected = "true" disabled="disabled"> Select one from below...</option>
                        <?php 
                            while ($rows=mysqli_fetch_assoc($result2))
                            {
                                $teachername= $rows['Username'];
                                echo"<option value ='$teachername'>$teachername</option>";
                            }
                         ?>
                    </select>    

    if(isset($_POST["btnAddclass"])){

        $classname = $_POST["classname"];
        $teacher = $_POST["teacher"];
        $subject = $_POST["subject"];
        $section = $_POST["section"];
        $yeargroup = $_POST["yeargroup"];

    $result1 = mysqli_query($conn, "SELECT ID FROM teacher INNER JOIN tbluser ON tbluser.ID=teacher.tbluser_ID WHERE Username = '$teacher'"); // using mysqli_query instead

    $sql = "INSERT INTO class (classname, teacher_id, yeargroup_id, subject_id, section_id) VALUES ('$classname', '$result1', '$subject','$section','$yeargroup')"; 
    if(!mysqli_query($conn,$sql))
    {
        echo "Error";
    }
    else 
    {
        echo "New class has been added.";
    }

    }

database

php sql database
1个回答
0
投票

也从tbluser中选择ID,该ID是教师ID:

$query = "SELECT ID, Username FROM tbluser WHERE Role='Teacher'";
$result2= mysqli_query($conn, $query);

<form action="createclass.php" method="POST">
    <div>
        <label>Class name</label>
        <input type="text" name="classname" class="form-control" placeholder="Enter new username">
        <label>Teacher</label>
        <select name="teacher">
            <option selected="true" disabled="disabled"> Select one from below...</option>
            <?php 
            while ($rows=mysqli_fetch_assoc($result2)) {?>
            <option value="<?php echo $rows['ID']?>"><?php echo $rows['Username']?></option>
            <?php
            }?>
        </select>

提交时:

$classname = $_POST["classname"];
$teacherID = $_POST["teacher"];
$subject = $_POST["subject"];
$section = $_POST["section"];
$yeargroup = $_POST["yeargroup"];

$sql = "INSERT INTO class (classname, teacher_id, yeargroup_id, subject_id, section_id) VALUES ('$classname', '$teacherID', '$subject','$section','$yeargroup')"; 

并且当您使用来自用户输入的不安全数据时,请考虑移至准备的语句以避免SQL注入。

© www.soinside.com 2019 - 2024. All rights reserved.