首页 > 开发 > PHP > 正文

PHP中在数据库中保存Checkbox数据(2)

2024-05-04 22:16:41
字体:
来源:转载
供稿:网友

这代码是非常简单的,你很快地就看完了吧。主要的工作有两个函数完成:"get_checkbox_labels" 和 "make_checkbox_html"。其中 "get_checkbox_labels" 查询表const_skills 并且返回一个对象数组,每一个对象有一个id值和相应的技能名称。我们传送这个数组和其它一些参数给"make_checkbox_html" ,这个函数将返回一个字串,用来生成checkbox的html代码。现在我们把这个字串插入html文件来生成我们需要的包含有各种技能选择的表单。注意我并没有传送变量 $checked 给"make_checkbox_html",这个参数是一个我们要显示的checked的对象数组。如果一个用户学会了一项新的技能,我们可以提供一个“编辑技能“页,显示的checkbox框中保存的用户的技能项应是被预先 checked。

用这种方法来动态创建一个表单相对于用一个固定的html代码来生成技能checkbox的好处在哪?嗯,或许我们允许求职者选择一个在我们的表const_skills中原先没有的项目,如DHTML,这样,我们可以将它插入表const_skills中,然后,求职者来访问我们的站点,就会发现多了一个DHTML选项。这一切无需调整html文件。

插入 lookup_skills

现在我们已经创建了这个表单,下面我们需要保存这个用户所选的技能。在make_checkbox_html函数中,我们用skill[]调用每一个选择项元素,意味着我们可以以数组元素的形式访问每个选择项。这样我们可以插入把这个选择插入表lookup_skill中。如果用户选中5个选项,我们就在lookup_skill中插入5条记录。记住在表lookup_skills中每一条记录只有两个字段用户id和技能id。在我的这个例子站点中,用户可以注册,然后能创建/编辑他们的简介。你可能要用session来保存userid,当他们登录后。但如何管理userid超过了本文的范围。

下面的代码,我们假定我们可能访问这个userid用这个变量名$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) {
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表