我上周刚刚开始使用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脚本,它将回显你提交表单时选择的值,所以我知道我可以检索我需要的值。我想我通常对如何将选项值存储在变量中以传递给查询感到困惑。任何帮助或参考帮助非常感谢!
答案 0 :(得分:1)
您似乎正在寻找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));
答案 1 :(得分:0)
通过阅读手册(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();