Home Database Mysql Tutorial PHP中在数据库中保存Checkbox数据_MySQL

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

Jun 01, 2016 pm 02:04 PM
str the keep data database

CheckBox

 介绍

  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;
}


? >

[第一节完]
----------------------------

作者:Dan LaFlamme
译者:sharetop(ycshowtop@21cn.com)
来源: www.phpbuilder.net
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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

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)

Slow Cellular Data Internet Speeds on iPhone: Fixes Slow Cellular Data Internet Speeds on iPhone: Fixes May 03, 2024 pm 09:01 PM

Facing lag, slow mobile data connection on iPhone? Typically, the strength of cellular internet on your phone depends on several factors such as region, cellular network type, roaming type, etc. There are some things you can do to get a faster, more reliable cellular Internet connection. Fix 1 – Force Restart iPhone Sometimes, force restarting your device just resets a lot of things, including the cellular connection. Step 1 – Just press the volume up key once and release. Next, press the Volume Down key and release it again. Step 2 – The next part of the process is to hold the button on the right side. Let the iPhone finish restarting. Enable cellular data and check network speed. Check again Fix 2 – Change data mode While 5G offers better network speeds, it works better when the signal is weaker

The vitality of super intelligence awakens! But with the arrival of self-updating AI, mothers no longer have to worry about data bottlenecks The vitality of super intelligence awakens! But with the arrival of self-updating AI, mothers no longer have to worry about data bottlenecks Apr 29, 2024 pm 06:55 PM

I cry to death. The world is madly building big models. The data on the Internet is not enough. It is not enough at all. The training model looks like "The Hunger Games", and AI researchers around the world are worrying about how to feed these data voracious eaters. This problem is particularly prominent in multi-modal tasks. At a time when nothing could be done, a start-up team from the Department of Renmin University of China used its own new model to become the first in China to make "model-generated data feed itself" a reality. Moreover, it is a two-pronged approach on the understanding side and the generation side. Both sides can generate high-quality, multi-modal new data and provide data feedback to the model itself. What is a model? Awaker 1.0, a large multi-modal model that just appeared on the Zhongguancun Forum. Who is the team? Sophon engine. Founded by Gao Yizhao, a doctoral student at Renmin University’s Hillhouse School of Artificial Intelligence.

Tesla robots work in factories, Musk: The degree of freedom of hands will reach 22 this year! Tesla robots work in factories, Musk: The degree of freedom of hands will reach 22 this year! May 06, 2024 pm 04:13 PM

The latest video of Tesla's robot Optimus is released, and it can already work in the factory. At normal speed, it sorts batteries (Tesla's 4680 batteries) like this: The official also released what it looks like at 20x speed - on a small "workstation", picking and picking and picking: This time it is released One of the highlights of the video is that Optimus completes this work in the factory, completely autonomously, without human intervention throughout the process. And from the perspective of Optimus, it can also pick up and place the crooked battery, focusing on automatic error correction: Regarding Optimus's hand, NVIDIA scientist Jim Fan gave a high evaluation: Optimus's hand is the world's five-fingered robot. One of the most dexterous. Its hands are not only tactile

The U.S. Air Force showcases its first AI fighter jet with high profile! The minister personally conducted the test drive without interfering during the whole process, and 100,000 lines of code were tested for 21 times. The U.S. Air Force showcases its first AI fighter jet with high profile! The minister personally conducted the test drive without interfering during the whole process, and 100,000 lines of code were tested for 21 times. May 07, 2024 pm 05:00 PM

Recently, the military circle has been overwhelmed by the news: US military fighter jets can now complete fully automatic air combat using AI. Yes, just recently, the US military’s AI fighter jet was made public for the first time and the mystery was unveiled. The full name of this fighter is the Variable Stability Simulator Test Aircraft (VISTA). It was personally flown by the Secretary of the US Air Force to simulate a one-on-one air battle. On May 2, U.S. Air Force Secretary Frank Kendall took off in an X-62AVISTA at Edwards Air Force Base. Note that during the one-hour flight, all flight actions were completed autonomously by AI! Kendall said - "For the past few decades, we have been thinking about the unlimited potential of autonomous air-to-air combat, but it has always seemed out of reach." However now,

Single card running Llama 70B is faster than dual card, Microsoft forced FP6 into A100 | Open source Single card running Llama 70B is faster than dual card, Microsoft forced FP6 into A100 | Open source Apr 29, 2024 pm 04:55 PM

FP8 and lower floating point quantification precision are no longer the "patent" of H100! Lao Huang wanted everyone to use INT8/INT4, and the Microsoft DeepSpeed ​​team started running FP6 on A100 without official support from NVIDIA. Test results show that the new method TC-FPx's FP6 quantization on A100 is close to or occasionally faster than INT4, and has higher accuracy than the latter. On top of this, there is also end-to-end large model support, which has been open sourced and integrated into deep learning inference frameworks such as DeepSpeed. This result also has an immediate effect on accelerating large models - under this framework, using a single card to run Llama, the throughput is 2.65 times higher than that of dual cards. one

AI startups collectively switched jobs to OpenAI, and the security team regrouped after Ilya left! AI startups collectively switched jobs to OpenAI, and the security team regrouped after Ilya left! Jun 08, 2024 pm 01:00 PM

Last week, amid the internal wave of resignations and external criticism, OpenAI was plagued by internal and external troubles: - The infringement of the widow sister sparked global heated discussions - Employees signing "overlord clauses" were exposed one after another - Netizens listed Ultraman's "seven deadly sins" Rumors refuting: According to leaked information and documents obtained by Vox, OpenAI’s senior leadership, including Altman, was well aware of these equity recovery provisions and signed off on them. In addition, there is a serious and urgent issue facing OpenAI - AI safety. The recent departures of five security-related employees, including two of its most prominent employees, and the dissolution of the "Super Alignment" team have once again put OpenAI's security issues in the spotlight. Fortune magazine reported that OpenA

iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos Jul 18, 2024 am 05:48 AM

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

How to handle database connection errors in PHP How to handle database connection errors in PHP Jun 05, 2024 pm 02:16 PM

To handle database connection errors in PHP, you can use the following steps: Use mysqli_connect_errno() to obtain the error code. Use mysqli_connect_error() to get the error message. By capturing and logging these error messages, database connection issues can be easily identified and resolved, ensuring the smooth running of your application.

See all articles