动态生成Checkbox表单
这段代码逻辑清晰,阅读起来并不困难。核心功能由两个函数承担:`get_checkbox_labels` 负责从 `const_skills` 表中检索数据,返回包含ID和技能名称的对象数组;`make_checkbox_html` 则接收该数组及其他参数,生成用于渲染复选框的HTML字符串。最终将此字符串嵌入页面以呈现技能选择表单。需注意,此处未向 `make_checkbox_html` 传递 `$checked` 变量,该变量通常用于预勾选已掌握的技能,以便在“编辑技能”页面回显用户历史选择。
相较于硬编码固定HTML,这种动态构建表单的方式优势在于灵活性。例如,若允许求职者添加表中不存在的新技能(如DHTML),系统可将其写入 `const_skills` 表。随后访问者即可看到新增选项,而无需修改任何HTML文件,实现了内容与结构的解耦。
插入 lookup_skills
保存用户选择至数据库
表单创建完成后,需处理数据持久化。在 `make_checkbox_html` 中,每个输入元素均命名为 `skill[]`,这使得后端能以数组形式获取所有选中值。据此,可将每条选择记录插入 `lookup_skills` 表。若用户选中五项,则对应插入五条记录。该表仅包含用户ID和技能ID两个字段。在实际应用中,用户登录后需通过Session维持UserID状态,但这部分会话管理超出本文讨论范围。
假设当前用户ID存储在变量 `$uid` 中,以下是执行插入操作的函数代码:
/* the function we call to insert.
the $skills argument is the skills array that
is sent to the script when the user hits the submit button
*/
function insert_skills($uid, $skills) {
/* first, we'll delete any entries this user already has
in the table */
purge_lookup("lookup_skills", $uid);
/* now create the sql insert query */
$query = create_checkbox_query($skills, "lookup_skills", $uid);
/* execute the query */
mysql_query($query);
}/* helper function for insert_skills().
removes all rows in $table with $uid */
function purge_lookup($table, $uid) {
$q = "DELETE FROM $table, WHERE uid = '$uid'";
mysql_query($q);
}/* helper function for insert_skills().
generates the sctual SQL query */
function create_checkbox_query($arr, $table, $uid) {
$q = "INSERT INTO $table (uid, skill_id) VALUES";
foreach ($arr as $check) {
$q .= " ( $uid , $check )" . ",";
}/* remove the last comma and return */
return substr($q, 0, -1);
}
?>
实现过程十分简洁。至此,我们掌握了如何从 `const_skill` 读取数据动态生成表单,以及如何将用户选择保存至 `lookup_skills` 表。接下来,我们将探讨如何利用这些数据进行技能搜索。
搜索
基于多选技能的SQL搜索查询
当雇主寻找具备特定技能的开发者时,可在搜索页复用上述表单,允许其筛选所需技能。获取选中技能数组后,可通过SQL查询找出拥有这些技能的求职者列表,并支持点击查看详情。以下函数展示了如何构建此类查询语句:
/* builds a query to search for the skills
checked off in the $skills array */
function skill_search($skills) {
if (!empty($skills)) {
$query = "SELECT DISTINCT user.username
FROM user, const_skills, lookup_skills
WHERE lookup_skills.uid = user.id
AND lookup_skills.skill_id = const_skills.id ";
$query .= " AND (";
foreach ($skills as $check) {
$query .= " const_skills.id = $check OR";
}/* remove the final OR */
$query = substr($query, 0, -2);
$query .= ")";
$count = count($skills);
$query .= " GROUP BY user.username HAVING count(user.username) >= $count";
$query .= ";";
return $query;
}
}
?>
若传入 PHP 和 Javascript 作为搜索条件,该函数生成的SQL语句如下:
SELECT DISTINCT user.username FROM user, const_skills, lookup_skills WHERE lookup_skills.uid = user.id AND lookup_skills.skill_id = const_skills.id AND ( const_skills.id = 3 OR const_skills.id = 5 ) GROUP BY user.username HAVING count(user.username) >= 2;
此函数实现的是逻辑“与”操作,即仅返回同时具备所选所有技能的求职者。例如选择 PHP 和 Javascript,结果只包含两者皆会的候选人。若需查找具备任一技能的候选人,可使用 `OR` 连接条件,并移除末尾的 `GROUP BY...` 子句以放宽限制。
总结
综上所述,Checkbox 是构建灵活表单的优秀元素。希望本文能协助读者利用该技术,更高效地开发数据驱动型网站应用。