简体   繁体   中英

PHP Mysql Fetch returning empty array

I'm trying to pull data from a MySQL table using PHP and I keep getting an empty array returned. Here's my code:

$gender = "'". $_POST['gender'] ."'";
        $ethnicity = "'".$_POST['ethnicity']."'";
        $job_desc = "'".$_POST['job_desc']."'";
        $title = "'".$_POST['title']."'";
        $nationality = "'".$_POST['nationality']."'";
        $department = "'".$_POST['department']."'";
        

        try {
            $stmt = $db_con->prepare("
                    SELECT * FROM `hr_list` WHERE 
                    `gender` = :gender AND 
                    `ethnic_origin` = :ethnicity AND 
                    `personnel_area` = :department AND 
                    `title` = :title AND 
                    `nationality` = :nationality AND 
                    `job_description` = :job_desc
                ");

            $stmt->bindParam(":gender", $gender);
            $stmt->bindParam(":ethnicity", $ethnicity);
            $stmt->bindParam(":job_desc", $job_desc);
            $stmt->bindParam(":title", $title);
            $stmt->bindParam(":nationality", $nationality);
            $stmt->bindParam(":department", $department);
            $stmt->execute();
            $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

I tried to echo the statement using the following and run it separately in Phpmyadmin and it gives me my result. But for some reason, PHP gives an empty array

echo "SELECT * FROM `hr_list` WHERE 
        `gender` = $gender AND 
        `ethnic_origin` = $ethnicity AND 
        `personnel_area` = $department AND 
        `title` = $title AND 
        `nationality` = $nationality AND 
        `job_description` = $job_desc";

How can I fix that?

there is no need for adding quote to the parameter

$gender = "'". $_POST['gender'] ."'";
        $ethnicity = "'".$_POST['ethnicity']."'";
        $job_desc = "'".$_POST['job_desc']."'";
        $title = "'".$_POST['title']."'";
        $nationality = "'".$_POST['nationality']."'";
        $department = "'".$_POST['department']."'";

You can remove "'". ... . "'" "'". ... . "'" "'". ... . "'" :

$gender = $_POST['gender'];
        $ethnicity = $_POST['ethnicity'];
        $job_desc = $_POST['job_desc'];
        $title = $_POST['title'];
        $nationality = $_POST['nationality'];
        $department = $_POST['department'];

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