如何通过url中的特定id从MySQL数据库获取数据

时间:2017-03-16 12:20:57

标签: php mysql

如何通过url中的特定ID从MySQL数据库获取数据

URL

http://localhost/php/edit_student.php?id=11

我的功能

function selected_students($connect){
$sentence = $connect->prepare('SELECT students.student_name, students.student_thumbnail FROM students JOIN courses_students ON courses_students.student_id = students.student_id JOIN courses ON courses_students.course_id = courses'.$_GET['id'].'GROUP BY courses_students.student_id');
$sentence->execute(array());
return $sentence->fetchAll();
}

1 个答案:

答案 0 :(得分:0)

正如我所提到的,您需要检查注释中$_GET['id']是否设置且不为空,当您使用prepare()时,您不能直接将变量注入查询中,您必须使用占位符,然后绑定并执行。 PDO有两种类型的占位符::PlaceHolderName?

 <?php
    function selected_students($connect)
    {

        if (isset($_GET['id']) && !empty($_GET['id'])) {

            $id = intval($_GET['id']);

            $sentence = $connect->prepare("SELECT students.student_name,students.student_id,students.student_thumbnail,courses_students.student_id,courses.course_id from students,courses join courses_students on students.student_id = courses_students.student_id and courses.course_id = ? GROUP BY courses_students.student_id");
            $sentence->execute([$id]);

            $results = $sentence->fetchall();

            if ($results > 0) {
                // Results exists display them



            }


        } else {

            // return error the id is not set
        }


    }
    ?>

以下是你可以学习pdo的好地方

https://phpdelusions.net/pdo

http://jayblanchard.net/demystifying_php_pdo.html