具有多个参数的PDO数据库搜索

时间:2017-12-29 21:40:47

标签: php mysql pdo

我试图在具有多个搜索参数的数据库中进行搜索。但是,我总是把整个表作为输出。用户应该在HTML表单中填写一个或多个字段。提交表单后,只显示与用户参数匹配的条目。当我只有一个参数时它工作正常。

这是我的代码:

if (isset($_POST['submit']))
{
    try
    {
        require "../config.php";
        require "../common.php";

        $connection = new PDO($dsn, $username, $password, $options);

        $sql = "SELECT *
                FROM medisGO_patient
                WHERE lastName LIKE '%" . $lastName . "%'
                AND firstName LIKE '%" . $firstName . "%'
                AND birthday LIKE '%" . $birthday . "%'
                AND course LIKE '%" . $course . "%'
                AND id LIKE '%" . $no . "%'";

        $lastName = trim($_POST['lastName']);
        $firstName = trim($_POST['firstName']);
        $course = trim($_POST['course']);
        $birthday = trim($_POST['birthday']);
        $no = trim($_POST['no']);

        $statement = $connection->prepare($sql);
        $statement->bindParam(':lastName', $lastName, PDO::PARAM_STR);
        $statement->bindParam(':firstName', $firstName, PDO::PARAM_STR);
        $statement->bindParam(':birthday', $birthday, PDO::PARAM_STR);
        $statement->bindParam(':course', $course, PDO::PARAM_STR);
        $statement->bindParam(':id', $no, PDO::PARAM_STR);
        $statement->execute();
        $result = $statement->fetchAll();

    }
    catch(PDOException $error)
    {
        echo $sql . "<br>" . $error->getMessage();
    }
}

1 个答案:

答案 0 :(得分:0)

您未在查询中使用参数,而是使用字符串连接。更糟糕的是,你联系了尚不存在的变量,所以PHP替换了一个空字符串。从本质上讲,您要构建的查询是:

SELECT *
FROM medisGO_patient
WHERE lastName LIKE '%%'
AND firstName LIKE '%%'
AND birthday LIKE '%%'
AND course LIKE '%%'
AND id LIKE '%%'

这就是你获得整张桌子的原因。

您应该使用命名参数,而应该在值中添加%符号:

$sql = "SELECT *
        FROM medisGO_patient
        WHERE lastName LIKE :lastName
        AND firstName LIKE :firstName
        AND birthday LIKE :birthday
        AND course LIKE :course
        AND id LIKE :id";

$lastName = '%' . trim($_POST['lastName']) . '%';
$firstName = '%' . trim($_POST['firstName']) . '%';
$course = '%' . trim($_POST['course']) . '%';
$birthday = '%' . trim($_POST['birthday']) . '%';
$no = '%' . trim($_POST['no']) . '%';

$statement = $connection->prepare($sql);
$statement->bindParam(':lastName', $lastName, PDO::PARAM_STR);
$statement->bindParam(':firstName', $firstName, PDO::PARAM_STR);
$statement->bindParam(':birthday', $birthday, PDO::PARAM_STR);
$statement->bindParam(':course', $course, PDO::PARAM_STR);
$statement->bindParam(':id', $no, PDO::PARAM_STR);
$statement->execute();