从用户表单定义的值返回客户列表php / sql form

时间:2017-02-26 02:05:25

标签: php mysql pdo

目前我正在开发一些代码,允许用户输入两个值(在这种情况下是两个邮政编码),并且在提交时,程序将返回等于和代码之间的值。例如,如果分别输入123456和234567作为开始和结束邮政编码,则它将返回仅具有该范围内的邮政编码的客户。

我已经能够通过直接在SQL命令中在预先确定的范围内进行硬编码来使用SQL。但我想用用户输入的变量来做这件事。我相信这将在最终的fetch命令中完成。

$SQL = "SELECT LastName, FirstName, Address1, City, State, Zip FROM Customers ORDER BY LastName ASC;";
try {
    $sth = $conn->prepare($SQL);
    $sth->execute();
} catch (PDOException $e) {
    echo "Error selecting customer records: " . $e->getMessage();
    die;
}

echo "Query excecuted successfully. <br />";

if($sth->rowCount()==0) {
    echo "No records returned. <br />";
    die;
} else {
    echo $sth->rowCount() . " records returned. <br /> <br />";
}

while($result = $sth->fetch()){
    //in an array, refer to column with string inside brackets ['rid']
    echo "LastName: " . $result['LastName'] . "<br />";
    echo "FirstName: " . $result['FirstName'] . "<br />";
    echo "Address1: " . $result['Address1'] . "<br />";
    echo "City: " . $result['City'] . "<br />";
    echo "State: " . $result['State'] . "<br />";
    echo "Zip: " . $result['Zip'] . "<br /> <br />";
}

在最初的$ SQL语句中,我可以使用WHERE Zip BETWEEN ## AND ##来获取我想要的内容,但我想使用用户定义的变量。我该怎么办呢?我看起来相当广泛,但我不能使用正确的条款。

1 个答案:

答案 0 :(得分:2)

使用占位符(?)并在->execute()中隐式绑定用户输入:

$zipFrom = $_POST['zipFrom'];
$zipTo   = $_POST['zipTo'];
// TODO: validate input data

$SQL = "SELECT LastName, FirstName, Address1, City, State, Zip 
        FROM Customers 
        WHERE Zip BETWEEN ? AND ?
        ORDER BY LastName ASC";
$sth = $conn->prepare($SQL);
$sth->execute([$zipFrom, $zipTo]);

您还可以使用命名占位符来提高查询的可读性:

$SQL = "SELECT LastName, FirstName, Address1, City, State, Zip 
        FROM Customers 
        WHERE Zip BETWEEN :zip_from AND :zip_to
        ORDER BY LastName ASC";
$sth = $conn->prepare($SQL);
$sth->execute([
    'zip_from' => $zipFrom,
    'zip_to'   => $zipTo
]);

您可以将代码放入try-catch-block中。但是,如果您只想转储错误消息,那就没有意义了。