我自告奋勇,想为我的学校创建一些有用的数据库,以便有效地跟踪学生的不当行为。我不是专家。我一直在做的是,我用Google搜索我想要的东西,自学它,并尝试将所有东西拼接在一起。
我遇到了这个教程,几乎是我想要的,我基于此在数据库上工作:http://www.yourinspirationweb.com/en/how-to-create-chained-select-with-php-and-jquery/
结果,我出来了:http://ipoh.wesleyschool.edu.my/ace_beta.php
整个想法是基于课程的选择,该特定班级的学生将作为一个列表出现。
目前整个过程都有效,但我想把它推到另一个层面。正如你所看到的,我写的只允许一个学生,如果我想同时选择多个学生同样的错误做什么呢?
我用Google搜索“动态复选框”等等,但不知怎的,我不知道要将它们联系起来,以使其正常工作......我已经尝试过,这就是为什么你在这里找我问。
CODE(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紧密相关...
CODE(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();
?>
问题
有人可以善意指导我,但如何做到以下几点:
答案 0 :(得分:0)
首先,您需要将数据库查询分成包含一个与数据库连接的类。为此,您需要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 />
我还没有测试过所有这些,但希望这有助于让你朝着正确的方向前进!