且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Mysql使用php下拉列表中的值选择查询

更新时间:2023-02-11 19:07:33

以下是我要为表单做的事情(假设您有一个正确的表单标签,其中的 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!