3

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

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

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

整个想法是基于班级的选择,该班级的学生会以列表的形式出现。

整个事情目前有效,但我想把它推到另一个层次。如您所见,我写的内容一次只允许一个学生,如果我希望同时选择多个学生做同样的错误怎么办?

我用谷歌搜索了“动态复选框”等,但不知何故我不知道将它们链接起来,让它发挥作用……我已经尝试过,这就是为什么你在这里找到我问的原因。

代码(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 中处理所选名称的方法。
4

1 回答 1

0

首先,您需要将数据库查询分离到拥有一个与数据库的连接的类中。要得到这个,你需要一个单例

/**
 * 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 />

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

于 2012-12-25T09:51:31.780 回答