php - PHP 脚本中的 HTML 复选框和 Mysql

标签 php html mysql checkbox drop-down-menu

我在mysql的一个表中存储了多个用户的信息。这些应该被分类为 5 个标签,A、B、C、D 和 E。信息存储在表中,如下所示:

  1. 也许上面提到的所有标签都被使用了
  2. 也许“A”被多次使用,与 B、C 等相同。
  3. 也许只使用了少数标签,而其他标签从未用于分类

我在由 php 脚本生成的 html 中为这些标签提供复选框选项,当用户选中部分或全部选项时,它应该从表中检索选中的标签信息并执行某些操作。

但就我而言,当检查某些标签并且这些标签未存储在表中时,我收到错误(显然,因为它们在表中没有标签信息)。那么,我应该如何编程,以便即使我检查了一些标签,并且它们的信息不在mysql表中,程序应该忽略它们并显示与其他检查标签相关的信息。我无法用 PHP 编写带有 MySQL 查询的程序。它可以是复选框或选择。

如果问题不清楚,请告诉我,因为用文字解释有点复杂。

最佳答案

据我最终了解,您希望根据用户通过复选框选择的选项来查询数据库。但是,如果用户无法选择多个选项,那么我建议您使用单选按钮,为所有单选按钮指定相同的名称,以便用户只能选择一个选项并运行您的代码,如下所示:

<form action="page.php" method="post">
    <input type="radio" name="tag" value="A" />
    <input type="radio" name="tag" value="B" />
    <input type="radio" name="tag" value="C" />
    <input type="submit" name="submit" />
</form>

那么你的 php 页面应该是这样的:

<?php

    //your db connection here

    if(isset($_POST['submit'])){
        $tag = $_POST['tag'];

        // remember you should use mysqli because mysql is deprecated and $c0n will be the variable assigned to your db connection
        $query = mysqli_query($con, "SELECT id FROM table WHERE tag='".$tag."'");

    }   

?>

但是,如果用户可以选择多个选项,那么您可以使用该复选框并像这样运行代码:

<form action="page.php" method="post">
    <input type="checkbox" name="a" />
    <input type="checkbox" name="b" />
    <input type="checkbox" name="c" />
    <input type="submit" name="submit" />
</form>

这应该是你的 php 页面:

<?php

    //your db connection here

    if(isset($_POST['submit'])){
        $tag1 = $_POST['a'];
        $tag2 = $_POST['b'];
        $tag3 = $_POST['c'];

        //here you assign variables to each checkbox if they are checked
        //but if they aren't you assign the variable to be null or anything
        //you wish as long as it won't tamper with your query

        if($tag1 == "on"){
            $a = "A";
        } else {
            $a = ""; //assign any wrong value here
        }
        if($tag2 == "on"){
            $b = "B";
        } else {
            $b = ""; //assign any wrong value here
        }
        if($tag3 == "on"){
            $c = "C";
        } else {
            $c = ""; //assign any wrong value here
        }

        // remember you should use mysqli because mysql is deprecated and $c0n will be the variable assigned to you db connection
        $query = mysqli_query($con, "SELECT id FROM table WHERE tag='".$a."' OR tag='".$c."' OR tag='".$c."'");

    }   

?>

希望这对您有帮助

关于php - PHP 脚本中的 HTML 复选框和 Mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37423447/

相关文章:

php - 如何通过匹配 url 中的变量向数据库插入值?

php - 在运行时在php中动态生成类?

mysql - 如何查询 2 个日期范围 (mysql)

php - PDO 事务不捕获异常

php - PHP 5.4.11 上 PDO::execute(array()) 的内部服务器错误

javascript - 两个 div 对齐问题之间的垂直线

javascript - 使用 dropzone 上传文件时出现问题

android - Unity HTML5(WebGL) 导出的项目无法在手机/平板电脑上运行

mysql - RMySQL安装: $operator is invalid for atomic vectors

检查 MYSQL 是否运行的 PHP 脚本?