Saving Checkbox data in the database in PHP (1)_PHP tutorial
Introduction
Checkbox is a very useful page form item. When allowing users to make multiple selections, it can even allow users to select all items or none. However, while this is a great form element, in our work there is always some confusion about how to properly save selections. This article will describe how to correctly save checkbox selections in the database while following good database design principles.
Requirements
This article will explain how to correctly save the selections in the user database. Although useful PHP code is included here, I will express it from a database design perspective, so you can easily implement it using any database and server-side scripting language. I just want to provide a how-to that you can apply to your own site. If you want to run the source code here, you need to install php, mysql and a web server.
Example 1: Recruitment site
Suppose you are asked to make a recruitment website that allows job-seeking software developers to fill in their skills so that employers can access the site and base their job search results on job seekers. Skills to find the right employees. You also know that a developer can have more than one skill set, so you decide to design your site that way.
Every job seeker will be allowed to visit this site, register as a user, and enter his skills. Checkbox will come in handy. You may want to make a page like this:
__ PHP __ MySQL __ Zope
__ Perl __ Javascript __ JSP
[Submit]
Every job applicant can choose the skills he possesses. Obviously the options are different for different people. One might be PHP and MySQL, others might just be JSP. How will you save these selections? A natural idea is to create a field for each option so that it works fine initially. But then you may find that trouble comes when you want to expand or adjust, and you may have to modify your table structure.
A good method should be like this:
You should have a user table containing the user's registration information, such as username, password and other content you need. If you directly use the source code given later in this article, you need to build a simple table as follows:
id username
1 User1
2 User2
3 User3
us First create a table "const_skills" using the following SQL statement:
SQL> CREATE TABLE const_skills (
id int not null primary key,
value varchar(20) );
Now we add skills:
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");
Your const_skills It should now look like this:
id value
1 PHP
2 MySQL
3 Zope
4 Perl
5 Javascript
6 JSP
This table only allows users to select the corresponding skills. Now, create another table lookup_skills using the following SQL:
SQL> CREATE TABLE lookup_skills (
id int not null auto_increment primary key,
uid int ,
skill_id int );
The purpose of this table lookup_skills is to provide a mapping relationship from the user table to the development skills table. In other words, it lets us save developers and the skills they have, so when a candidate completes their selection and clicks submit, we will fill in the form with those values selected in the checkbox. For each selected skill, we add a record to this table and record the user ID and the ID of the selected item. (I believe everyone knows this. I translated this, hehe...)
Before we look at the code for inserting records, let’s design this page first. There should be a form for the content that we can query database and take the checkbox label from the const_skills table to create this checkbox form item.
代码如下:
< ?php
/* 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[]");
? >
< html >
< body >
< br >
< form name="skills" method="POST" action="insertskills.php" >
Check off your web development skills:
< ? echo "$html_skills"; ? >
< br >
< input type="submit" value="Submit" >
< /form >
< /body >
< /html >
< ?php
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 .= "< table width="$width" border="0" >n";
$str .= "< tr >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 .= "< td >< input type="checkbox" name="$name" value="$ele- >id"";
foreach ($checked as $entry) {
if ($entry == $ele- >value) {
$str .= "checked";
continue;
}
}
$str .= " >";
$str .= "$ele- >value";
if ($i % $num == 0) {
$str .= "< /tr >n< tr >";
} else {
$str .= "< /td >n";
}
$i++;
}
} else {
/* we just want to print the checkboxes. none will have checks */
foreach ($arr as $ele) {
$str .= "< td >< input type="checkbox" name="$name" value="$ele- >id" >";
$str .= "$ele- >value";
if ($i % $num == 0) {
$str .= "< /tr >n< tr >";
} else {
$str .= "< /td >n";
}
$i++;
}
}
/* tack on a closing tr tag if necessary */
if ($closingTR == true) {
$str .= "< /tr >< /table >n";
} else {
$str .= "< /table >n";
}
return $str;
}
? >

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

In PHP, you can effectively prevent CSRF attacks by using unpredictable tokens. Specific methods include: 1. Generate and embed CSRF tokens in the form; 2. Verify the validity of the token when processing the request.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.
