HTML / PHP / SQL - 使用参数查询

时间:2013-11-22 00:41:16

标签: php mysql sql pdo

这是我的代码:

<form action="" method="post">
        <fieldset>
            Date 1: <input type="text" name="date1">
            Date 2: <input type="text" name="date2">
        </fieldset>
            <button type="submit" name="Search">
    </form>

    <?php
    try {
        $db = new PDO('mysql:host=localhost;dbname=db;charset=utf8', 'user', 'pass');
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (Exception $e) {
        echo "DB is down";
        exit; 
    }

    try {
        $results = $db->query("SELECT * FROM instructor WHERE date_hired BETWEEN ? AND ?"); 
    } catch (Exception $e) {
        echo "No data found";
        exit;
    }

    echo "<pre>";
    var_dump($results->fetchAll(PDO::FETCH_ASSOC));

    ?> 

如何更改PHP代码以使用我创建的表单来获取参数?

我希望能够在表单中输入2个日期,因此它会进入查询,然后输出结果。

2 个答案:

答案 0 :(得分:2)

更改此行:

$results = $db->query("SELECT * FROM instructor WHERE date_hired BETWEEN ? AND ?");

$results = $db->prepare("SELECT * FROM instructor WHERE date_hired BETWEEN ? AND ?");
$results->execute(array($_POST['date1'], $_POST['date2']));

此外,这是一个很好的链接,可以帮助您入门:

http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers

答案 1 :(得分:1)

使用占位符执行语句时,必须提供绑定数据:

$sth = $db->prepare("SELECT * FROM ... BETWEEN ? AND ?");
$results = $sth->execute(array($start, $end));