使用表单选项值作为PHP变量来执行准备好的SQL语句


Using a form option value as a PHP variable to execute prepared SQL statement

我上周才开始使用PHP,我一直在寻找解决这个问题的方法,但是我不能把我的大脑集中在我遇到的答案上。

在index。html:

中有这样一个表单
<form method="post" action="actionTest.php">
    <select name="courseID">
        <option value = "111">Course 1</option>
        <option value = "222"> Course 2 </option>
        <option value ="333"> Course 3 </option>
    </select>
    <input type="submit" />
</form> 

然后是actiontest。php文件中的预处理语句

//variable for selected option value?
//$courseSelect = [???]
//query
$sql = "SELECT * FROM courses WHERE course_id = ?";
//prepare the query
$q = $con->prepare($sql);
//execute the statement
$q->execute();
//setting fetch mode for statement
$q->setFetchMode(PDO::FETCH_ASSOC);
//display fetched data
while($r = $q->fetch()){
    echo $r['name'] . "'n";
    echo $r['course_id'] . "'n";
    echo $r['description'] . "'n";
    echo "</br>";
}
我已经编写了一个简单的PHP脚本,它将在您提交表单时返回所选择的值,因此我知道我可以检索我需要的值。我想我通常对如何将选项值存储在变量中以传递给查询感到困惑。任何帮助或参考帮助是非常感激的!

您似乎正在寻找PDO bindParam()

首先,获取张贴的值。以下代码将变量设置为false,如果没有发送值:

$course_id= isset($_POST['courseID']) ? $_POST['courseID'] : false;

然后准备你的查询:

// query
$sql = "SELECT * FROM courses WHERE course_id = ?";
// prepare query
$q = $con->prepare($sql);
// bind the parameter to the query
$q->bindParam(1,$course_id,PDO::PARAM_INT);
//execute the statement
$q->execute();
//display fetched data
while($r = $q->fetch(PDO::FETCH_ASSOC)){
    echo $r['name'] . "'n";
    echo $r['course_id'] . "'n";
    echo $r['description'] . "'n";
    echo "</br>";
}

或者,在您的上下文中,您可以跳过绑定,只使用参数执行:

$q->execute(array($course_id));

通过阅读手册(http://nl1.php.net/pdo.prepared-statements),您可以以这种方式绑定参数:

$q = "SELECT * FROM courses WHERE course_id = ?";
$q->bindParam(1, $myValue, PDO::PARAM_INT);
// insert one row
$myValue = $_POST['courseID'];
$q->execute();