Mysql使用php下拉列表中的值选择查询 [英] Mysql select query using value from a php dropdown
问题描述
我开始用 php 编程,但我有一点疑问.
I started programming in php and I'm having a small doubt.
我正在尝试使用下拉列表中的值搜索数据库.
I'm trying to do a search the database using a value from a dropdown.
问题是查询总是使用下拉列表的最后一个值.
The problem is that the query always uses the last value of the dropdown.
有人能帮我找出错误吗?
Does anyone can help me find the error?
为什么 where 子句中的研究总是下拉列表的最后一个值?
Why is research in where clause is always the last value of the dropdown?
代码
<tr><td>Technical:</td><td>
<select>
<?php
$query = "SELECT idTechnical, name FROM technicals";
$result2 = mysql_query($query);
$options="";
while($row=mysql_fetch_array($result2)){
$id=$row["idTechnical"];
$thing=$row["name"];
echo "<OPTION VALUE=$id>$thing</option>";
}
?>
</select>
<?php
if (isset($_POST['Next'])) {
if($_REQUEST['Next']=='Search') {
{
$sql="select idTask, descTask, deadline, idTechnical from tasks where idTechnical = '$id' order by deadline desc";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
}
}
}
?>
我从下拉列表中选择任何值,但只使用 where 子句中的最后一个值
I select any value from dropdown, but only uses the last value in clause where :S
推荐答案
以下是我要为表单做的事情(假设您有一个正确的表单标签,其中的 action 属性指向正确的 PHP 脚本):
Here is what I would do for the form (assuming you have a proper form tag with an action attribute that points to the correct PHP script):
<tr>
<td>Technical:</td>
<td>
<select name="technical">
<?php
$query = "SELECT idTechnical, name FROM technicals";
$result2 = mysql_query($query);
$options="";
while($row=mysql_fetch_array($result2)){
echo '<option value='.$row["idTechnical"].'>
'.$row["name"].'
</option>';
}
?>
</select>
</td>
然后在 PHP 脚本中:
Then in the PHP script:
$sql='SELECT
idTask,
descTask,
deadline,
idTechnical
FROM tasks
WHERE idTechnical = '.$_REQUEST['technical'].'
ORDER BY deadline DESC';
$result=mysql_query($sql);
$count=mysql_num_rows($result);
这应该适合你.
但请注意:上面的脚本存在安全风险,因为它为 SQL 注入敞开了大门
更好的方法是使用 PDO Prepared 语句,如下所示:
A better way to do this would be to use a PDO Prepared statement, like this:
$db = new PDO('mysql:host=CHANGE_THIS_TO_YOUR_HOST_NAME;
dbname=CHANGE_THIS_TO_YOUR_DATABASE',
'CHANGE_THIS_TO_YOUR_USERNAME',
'CHANGE_THIS_TO_YOUR_PASSWORD');
$sql='SELECT
idTask,
descTask,
deadline,
idTechnical
FROM tasks
WHERE idTechnical = :id
ORDER BY deadline DESC';
$query = $db->prepare($sql);
$query->bindValue(':id', $_REQUEST['technical']);
$query->execute();
$count = $query->rowCount();
如果您刚开始使用 PHP,我强烈建议您花一些时间熟悉 PDO 数据库查询.祝你好运,编码愉快!
If you're just starting in PHP, I would highly recommend that you spend some time to become familiar with PDO Database querying. Good luck and happy coding!
这篇关于Mysql使用php下拉列表中的值选择查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!