Home php教程 php手册 PHP中在数据库中保存Checkbox数据

PHP中在数据库中保存Checkbox数据

Jun 21, 2016 am 08:58 AM
const query the

数据|数据库

介绍

  checkbox是一个非常有用的页面表单项,在让用户进行多重选择的情况下,它甚至可以允许用户选择全部项目或是一个都不选。但是,尽管这是一个非常优秀的表单元素,但在我们的工作中,在如何正确地保存选择项这方面总存在一些易混淆的情况发生。本文将描述在遵循好的数据库设计原则的方法下,如何把checkbox选择项正确地保存在数据库中。

要求

  本文将阐述如何把选择项正确地保存在用户数据库中的方法。尽管这里包括了有用的PHP代码,但我将从数据库设计的观点来表达它们,所以,你可以很方便地使用任何一个数据库和服务器端脚本语言来实现。我只是想提供一个如何做的方法,让你能应用于你自己的站点中。如果你想运行这里的源码,你需要安装php、mysql和网络服务器。

例1:招聘站点

  假如你被要求做一个招聘类的网站,允许求职的软件开发人员填写他们的技能,让雇主能访问这个站点并根据求职者的技能找到合适的员工。你也知道,一个开发人员拥有的技能会多于一个,因此你决定这样设计你的站点。

  每一个求职者将允许访问本站,注册一个用户,并且输入他的技能,Checkbox就派上用场了,你可能想作这样的一页:

__ PHP __ MySQL __ Zope
__ Perl __ Javascript __ JSP

[提交]

  每一个求职都可以选择他所拥有的技能。显然对于不同人来说这选择项是不同的。一个人可能会是PHP和Mysql,其它人可能只是JSP。你将如何保存这些选择呢?一个很自然的想法是针对每个选项建一个字段,这样开始可以正常工作。但是随后你可能会发现,当你想扩展或调整时,麻烦就来了,你可能不得不修改你的表结构。
好的方法应是这样的:

  你应有一个用户表包含用户的注册信息,如用户名、密码和其它一些你需要的什么内容。假如你直接使用本文后面给出的源码,你要建一个简单的表如下:

id username
1 User1
2 User2
3 User3

我们先建一个表 "const_skills" 用如下的 SQL 语句:

SQL> CREATE TABLE const_skills (
id int not null primary key,
value varchar(20) );

现在我们加入技能:

SQL> INSERT INTO const_skills(id, value) VALUES (1, "PHP");
SQL> INSERT INTO const_skills(id, value) VALUES (2, "MySQL");
SQL> INSERT INTO const_skills(id, value) VALUES (3, "Zope");
SQL> INSERT INTO const_skills(id, value) VALUES (4, "Perl");
SQL> INSERT INTO const_skills(id, value) VALUES (5, "Javascript");
SQL> INSERT INTO const_skills(id, value) VALUES (6, "JSP");

你的 const_skills 现在应是这样的:

id value
1 PHP
2 MySQL
3 Zope
4 Perl
5 Javascript
6 JSP

这个表只是让用户可以选择相应的技能,现在,再建一个表 lookup_skills 用如下的SQL:

SQL> CREATE TABLE lookup_skills (
id int not null auto_increment primary key,
uid int,
skill_id int );

  这个表lookup_skills的目的是提供从用户表到开发技能表之间的一个映射关系。换句话说,它让我们保存开发者和他们有的技能,如,当求职者完成选择点击提交时,我们将填写这个表用checkbox中被选定的那些值。对于每一个选上的技能,我们在这个表中加一条记录,记下用户id及所选项的id。(想必大家都清楚了吧。我译到这,嘿嘿…)

在我们看这个插入记录的代码之前,我们先设计一下这个页面,应有的内容有一个表单,我们可以查询的数据库并且取checkbox标签从const_skills表中,建这个checkbox表单项。

代码如下:


/* insert code to connect to your database here */

/* get the checkbox labels */
$skills = get_checkbox_labels("const_skills");

/* create the html code for a formatted set of
checkboxes */
$html_skills = make_checkbox_html($skills, 3, 400, "skills[]");

? >





Check off your web development skills:








function get_checkbox_labels($table_name) {

/* make an array */
$arr = array();

/* construct the query */
$query = "SELECT * FROM $table_name";

/* execute the query */
$qid = mysql_query($query);

/* each row in the result set will be packaged as
an object and put in an array */
while($row= mysql_fetch_object($qid)) {
array_push($arr, $row);
}

return $arr;
}

/* Prints a nicely formatted table of checkbox choices.

$arr is an array of objects that contain the choices
$num is the number of elements wide we display in the table
$width is the value of the width parameter to the table tag
$name is the name of the checkbox array
$checked is an array of element names that should be checked
*/

function make_checkbox_html($arr, $num, $width, $name, $checked) {

/* create string to hold out html */
$str = "";

/* make it */
$str .= "n";
$str .= "n";

/* determine if we will have to close add
a closing tr tag at the end of our table */
if (count($arr) % $num != 0) {
$closingTR = true;
}

$i = 1;
if (isset($checked)) {
/* if we passed in an array of the checkboxes we want
to be displayed as checked */
foreach ($arr as $ele) {
$str .= "id"";
foreach ($checked as $entry) {
if ($entry == $ele- >value) {
$str .= "checked";
continue;
}
}
$str .= " >";
$str .= "$ele- >value";

if ($i % $num == 0) {
$str .= "n";
} else {
$str .= "n";
}
$i++;
}

} else {
/* we just want to print the checkboxes. none will have checks */
foreach ($arr as $ele) {
$str .= "id" >";
$str .= "$ele- >value";

if ($i % $num == 0) {
$str .= "n";
} else {
$str .= "n";
}
$i++;
}

}

/* tack on a closing tr tag if necessary */
if ($closingTR == true) {
$str .= "n";
} else {
$str .= "n";
}

return $str;
}

? >
  这代码是非常简单的,你很快地就看完了吧。主要的工作有两个函数完成:"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) {
$q .= " ( $uid , $check )" . ",";
}

/* remove the last comma and return */
return substr($q, 0, -1);
}

?>

  很简单吧。现在你知道如何从表const_skill读记录来动态创建一个表单,也知道如何保存用户选择的技能到表lookup_skills中。下面我们要做什么?让我们看一下搜索吧
搜索

  当一个雇主来找一个网络开发人员时,他来到你的搜索页面,你可以显示同样的一个表单并且允许他选择他想要雇员拥有的技能。你取到了他选中的技能的数组,然后你可以遍历这个数组,用一个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 ,这个函数返回这个语句:

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 两项,只会返回*同时*拥有PHP 和 Javascript两种技能的求职者的username。如果你想要找拥有其中任一个技能的求职者,你可以用 PHP *OR* Javascript ,如果你想显示相同的记录,你可以去掉最后的"GROUP BY..." 子句。


  总结

  好了,就是这样。checkboxes是一个优秀的表单元素,正如本文所谈论的。我希望这有助于你用它们来工作,创建一个数据驱动的网站。



Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
After 2 months, the humanoid robot Walker S can fold clothes After 2 months, the humanoid robot Walker S can fold clothes Apr 03, 2024 am 08:01 AM

Editor of Machine Power Report: Wu Xin The domestic version of the humanoid robot + large model team completed the operation task of complex flexible materials such as folding clothes for the first time. With the unveiling of Figure01, which integrates OpenAI's multi-modal large model, the related progress of domestic peers has been attracting attention. Just yesterday, UBTECH, China's "number one humanoid robot stock", released the first demo of the humanoid robot WalkerS that is deeply integrated with Baidu Wenxin's large model, showing some interesting new features. Now, WalkerS, blessed by Baidu Wenxin’s large model capabilities, looks like this. Like Figure01, WalkerS does not move around, but stands behind a desk to complete a series of tasks. It can follow human commands and fold clothes

Deep understanding of const in C language Deep understanding of const in C language Feb 18, 2024 pm 12:56 PM

Detailed explanation and code examples of const in C In C language, the const keyword is used to define constants, which means that the value of the variable cannot be modified during program execution. The const keyword can be used to modify variables, function parameters, and function return values. This article will provide a detailed analysis of the use of the const keyword in C language and provide specific code examples. const modified variable When const is used to modify a variable, it means that the variable is a read-only variable and cannot be modified once it is assigned a value. For example: constint

How to reorder multiple columns in Power Query via drag and drop How to reorder multiple columns in Power Query via drag and drop Mar 14, 2024 am 10:55 AM

In this article, we will show you how to reorder multiple columns in PowerQuery by dragging and dropping. Often, when importing data from various sources, columns may not be in the desired order. Reordering columns not only allows you to arrange them in a logical order that suits your analysis or reporting needs, it also improves the readability of your data and speeds up tasks such as filtering, sorting, and performing calculations. How to rearrange multiple columns in Excel? There are many ways to rearrange columns in Excel. You can simply select the column header and drag it to the desired location. However, this approach can become cumbersome when dealing with large tables with many columns. To rearrange columns more efficiently, you can use the enhanced query editor. Enhancing the query

React Query database plug-in: how to import and export data React Query database plug-in: how to import and export data Sep 26, 2023 pm 05:37 PM

ReactQuery database plug-in: Methods to implement data import and export, specific code examples are required. With the widespread application of ReactQuery in front-end development, more and more developers are beginning to use it to manage data. In actual development, we often need to export data to local files or import data from local files into the database. In order to implement these functions more conveniently, you can use the ReactQuery database plug-in. The ReactQuery database plugin provides a series of methods

18 Ways to Fix Audio Service Not Responding Issue on Windows 11 18 Ways to Fix Audio Service Not Responding Issue on Windows 11 Jun 05, 2023 pm 10:23 PM

Audio output and input require specific drivers and services to work as expected on Windows 11. These sometimes end up running into errors in the background, causing audio issues like no audio output, missing audio devices, distorted audio, etc. How to Fix Audio Service Not Responding on Windows 11 We recommend you to start with the fixes mentioned below and work your way through the list until you manage to resolve your issue. The audio service may become unresponsive for a number of reasons on Windows 11. This list will help you verify and fix most issues that prevent audio services from responding on Windows 11. Please follow the relevant sections below to help you through the process. Method 1: Restart the audio service. You may encounter

C++ syntax error: const objects must be initialized when defined, how to deal with it? C++ syntax error: const objects must be initialized when defined, how to deal with it? Aug 22, 2023 am 09:13 AM

For C++ programmers, syntax errors are one of the most common problems. One of the common mistakes is that const objects must be initialized at definition time. If you encounter this situation, how should you deal with it? First, we need to understand what a const object is. The const keyword is a special type qualifier in C++ that specifies that the value of a variable cannot be changed during the execution of the program. Such variables are called "constants". If you define a const object without initializing it, you will encounter the above error. This is

What are the correct uses of the const keyword in C++ functions? What are the correct uses of the const keyword in C++ functions? Apr 11, 2024 pm 02:36 PM

Correct usage of the const keyword in C++: Using const to modify a function means that the function will not modify the parameters or class members passed in. Using const to declare a function pointer means that the pointer points to a constant function.

How to use const in c language How to use const in c language Sep 20, 2023 pm 01:34 PM

const is a keyword that can be used to declare constants, const modifiers in function parameters, const modified function return values, and const modified pointers. Detailed introduction: 1. Declare constants. The const keyword can be used to declare constants. The value of the constant cannot be modified during the running of the program. The constant can be a basic data type, such as integer, floating point number, character, etc., or a custom data type; 2. The const modifier in the function parameters. The const keyword can be used in the parameters of the function, indicating that the parameter cannot be modified inside the function, etc.

See all articles