来自 SQL 的 PHP 动态复选框列表,基于级联选择选择

标签 php jquery mysql

我自愿并想为我的学校创建某种数据库,以有效地跟踪学生的不当行为。我不是专家。我一直在做的是,我在 Google 上搜索我想要的东西,自学它,然后尝试将所有内容拼接在一起。

我遇到了这个教程,几乎是我想要的,我基于这个在数据库上工作:http://www.yourinspirationweb.com/en/how-to-create-chained-select-with-php-and-jquery/

结果,我得出了这个:http://ipoh.wesleyschool.edu.my/ace_beta.php

整个想法是基于类(class)的选择,该类(class)的学生将作为列表出现。

目前一切正常,但我想将其推向另一个层次。正如你所看到的,我写的一次只允许一个学生,如果我想同时选择多个学生做同样的错误怎么办?

我在 Google 上搜索了“动态复选框”等,但不知何故我不知道如何将它们链接起来以使其正常工作......我已经尝试了又试了,这就是为什么你会发现我在这里提问。

代码(ace_beta.php):

主页面运行于:ace_beta.php;其中我相信我被困在这个地方:

<td width="25%" valign="top"'>

<table border="0" width="100%" cellpadding="6">
<tr>
<td width="100%" align="middle" valign="top" bgcolor='#636363'>
<font face="Arial" size='5' color='#ffffff'><b> STEP ONE </b></font>
</td></tr></table>

<br />
<b> STUDENT INFORMATION ::. </b>
<br />

<table border="0" width="100%" cellpadding="3">

<tr>
<td width="20%" align="right"> class </td>
<td width="80%" align="left">
    <select id="class" name="class">
        <?php echo $opt->ShowClass(); ?>
    </select></td>
</tr>

<tr>
<td width="20%" align="right"> student </td>    
<td width="80%" align="left">
    <select id="student" name="student">
         <option value="0">choose...</option>
         </select></td>
</tr>

</table>

</td>

ace_beta.php 与存储函数的 select.class.php 紧密相关...

代码 (select.class.php)

<?php
class SelectList
{
    protected $conn;

        public function __construct()
        {
            $this->DbConnect();
        }

        protected function DbConnect()
        {
            include "db_config.php";
            $this->conn = mysql_connect($host,$user,$password) OR die("Unable to connect to the database");
            mysql_select_db($db,$this->conn) OR die("can not select the database $db");
            return TRUE;
        }

        public function ShowClass()
        {
            $sql = "SELECT * FROM class";
            $res = mysql_query($sql,$this->conn);
            $class = '<option value="0">choose...</option>';
            while($row = mysql_fetch_array($res))
            {
                $class .= '<option value="' . $row['id_cls'] . '">' . $row['name'] . '</option>';
            }
            return $class;
        }

        public function ShowStudent()
        {
            $sql = "SELECT * FROM student WHERE id_cls=$_POST[id]";
            $res = mysql_query($sql,$this->conn);
            $student = '<option value="0">choose...</option>';
            while($row = mysql_fetch_array($res))
            {
                $student .= '<option value="' . $row['id_stu'] . '">' . $row['name'] . '</option>';
            }
            return $student;
        }

}

$opt = new SelectList();

?>

问题

有人可以指导我如何执行以下操作吗:

  1. 基于 ace_beta.php 中的“类选择”,一个复选框列表 轴承相应的学生会出现在“学生 ace_beta.php 的区域”
  2. 处理选中名字的方法,在ace_add.php之后 点击“提交”按钮。

最佳答案

首先,您需要将数据库查询分离到一个类中,该类包含一个到数据库的连接。为此,您需要 singleton .

/**
 * Simple DB class as Singleton.
 */
class Database {

    /**
     * @var PDO
     */
    protected $conn;

    /**
     * @var Database
     */
    private static $instance;

    /**
     * Method that ensures you have only one instance of database
     *
     * @return Database
     */
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    /**
     * Query method.
     *
     * @example Database::getInstance()->query("SELECT * FROM table where param1 = ? AND param2 = ?", array($param1, $param2));
     *
     * @param string $sql
     *
     * @return array
     */
    public function query($sql) {
        $statement = $this->conn->prepare($sql);
        $args = func_get_args();
        array_shift($args);
        $statement->execute($args);
        return $statement->fetchAll(PDO::FETCH_ASSOC);
    }

    /**
     * Gets connection
     *
     * @return PDO
     */
    public function getConnection() {
        return $this->conn;
    }

    protected function DbConnect()
    {
        include "db_config.php";

        $dsn = sprintf('mysql:dbname=%s;host=%s', $db, $host);

        try {
            $this->conn = new PDO($dsn, $user, $password,

                // be sure you are have ut8 symbols
                array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''));

            // all errors from DB are exceptions
            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);


        } catch (PDOException $e) {
            echo 'Connection failed: ' . $e->getMessage();
            return FALSE;
        }

        return TRUE;
    }

    private function __construct()
    {
        $this->DbConnect();
    }

    private function __clone() {}
    private function __wakeup() {}

}

我已经稍微修改了你的代码。现在看起来更简单了,是吗?

class SelectList
{

    /**
     * Get class list
     *
     * @return array
     */
    public function getClass()
    {
        $sql = "SELECT * FROM class";
        $res = Database::getInstance()->query($sql);

        return $res;
    }

    /**
     * Get list of students from $classId
     *
     * @param int $classId class students from
     *
     * @return array
     */
    public function getStudent($classId)
    {
        $sql = "SELECT * FROM student WHERE id_cls= ?";

        $res = Database::getInstance()->query($sql, array($classId));

        return $res;
    }

}

这是您更改后的 ace_beta.php

<!--
 considering you are have form that looks like
 <form method="post" action="ace_beta.php">


 and somewhere you are have submit button :)
-->

<td width="25%" valign="top">

    <table border="0" width="100%" cellpadding="6">
        <tr>
            <td width="100%" align="middle" valign="top" bgcolor='#636363'>
                <font face="Arial" size='5' color='#ffffff'><b> STEP ONE </b></font>
            </td></tr></table>

    <br />
    <b> STUDENT INFORMATION ::. </b>
    <br />

    <table border="0" width="100%" cellpadding="3">

        <tr>
            <td width="20%" align="right"> class </td>
            <td width="80%" align="left">
                <select id="class" name="class">
                    <option value="0">choose...</option>
                    <?php foreach ($opt->getClass() as $class): ?>
                        <option value="<?php echo $class['id_cls'] ?>"><?php echo $class['name'] ?></option>
                    <?php endforeach; ?>
                </select>
            </td>
        </tr>

        <tr>
            <td width="20%" align="right"> student </td>
            <td width="80%" align="left">
                <div id="students">

                </div>
            </td>
        </tr>

    </table>

</td>

现在开始你的任务:

为了获得学生的复选框,您需要使用 AJAX .为此,您需要有一个单独的文件,例如 get_students.php

include 'select.class.php';
$opt = new SelectList();

// watch if there are any GET request coming with `class=ID`
if (isset($_GET['class'])) {
    $result = $opt->getStudent($_GET['class']);
    // header for JSON
    header('Content-type: application/json');
    // output JSON (need php 5.2 at least)
    echo json_encode($result);
}

添加到页面底部某处的 ace_beta.php

<!-- this just in case you are have no jQuery yet. -->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        // when you slect new item.
        $('#class').change(function(){
            $.ajax({
                // go to url with ?class=ID
                url: '//get_students.php?class=' + $(this).val(),
                dataType: 'json'
                // when all is ok:
                success: function(data){
                    var studentsContainer = $('#students');
                    // empty checkboxes.
                    studentsContainer.html('');

                    // iterate throug data
                    $.each(data, function(index, item) {
                        // create new checkobx
                        var checkbox = $('<input type="checkbox" name="students[]" />');
                        // assign value and id for it.
                        checkbox.attr('value', item.id)
                                .attr('id', 'student_' + item.id);

                        // create a label with name inside
                        var label = $('<label />');
                        label.attr('for', 'student_' + item.id);
                        label.html(item.name);

                        // append all of new elements and "<br />" for readability.
                        studentsContainer.append(checkbox);
                        studentsContainer.append(label);
                        studentsContainer.append('<br />');
                    });
                }
            });
        });
    });
</script>

上面的 javascript 将创建以下 HTML:

<input type="checkbox" name="students[]" value="1" id="student_1" /><label for="student_1" /><br />
<input type="checkbox" name="students[]" value="2" id="student_2" /><label for="student_2" /><br />
<input type="checkbox" name="students[]" value="3" id="student_3" /><label for="student_3" /><br />

我还没有测试所有这些,但希望这有助于让您朝着正确的方向前进!

关于来自 SQL 的 PHP 动态复选框列表,基于级联选择选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14028462/

相关文章:

php - 如何查询MySQL以获取与正在搜索的值相似或精确的值,并预先确定精确值?

javascript - PHP/MYSQL JavaScript - 将多个动态行的值插入文本字段

javascript - 将脚本 src 包含到 js 文件中

mysql - 使用许多连接优化 SQL 查询

php - 原则 2 - 如何在多个 addSelect 中添加限制

php - Mercurial 更新之间的数据库同步

javascript - 从函数中的 id 访问号码

javascript - 在新打开的窗口中打开另存为对话框

mysql - 如何创建一个没有密码的 MySQL 用户 - 远程登录需要 - 用于 bash 插入脚本?

php时间函数