使用 PHP 在 MySQL 数据库中存储多个复选框数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9561073/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Storing Multiple Checkbox Data in MySQL Database with PHP
提问by drummer392
I want to have multiple checkbox values be stored into one field in a database. (Ex. 1, 24,56,100). I am wanting to know how I can make this happen, and how does PHP read these values from the database if I want to call variables in a query?
我想将多个复选框值存储到数据库中的一个字段中。(例 1, 24,56,100)。我想知道如何实现这一点,如果我想在查询中调用变量,PHP 如何从数据库中读取这些值?
Basically I am creating a blog app (for fun and experience) and I want the user to be able to change the visibility of each blog post through checkboxes. I know you are probably thinking why don't I just have a visibility field for each blog post. I understand why it is not recommended to do this, but I can't think of any other way to do this. To explain a bit more: I want to attach this application to a CMS I have already built, and basically I have a table with blog posts, and then I want the user to be able to go to different pages within their site and add a blog. Well, what if the user wants to use the same blog on 3 different pages, but only wants certain posts to show on each page. So this is why I am confused right now.
基本上我正在创建一个博客应用程序(为了乐趣和体验),我希望用户能够通过复选框更改每个博客文章的可见性。我知道您可能在想为什么我不为每篇博文设置一个可见性字段。我理解为什么不建议这样做,但我想不出任何其他方法来做到这一点。再解释一下:我想将此应用程序附加到我已经构建的 CMS,基本上我有一个包含博客文章的表格,然后我希望用户能够转到其站点中的不同页面并添加一个博客。好吧,如果用户想在 3 个不同的页面上使用同一个博客,但只想在每个页面上显示某些帖子怎么办。所以这就是为什么我现在很困惑。
回答by Jaspreet Chahal
Even though I am not in favor of saving data like that but here is what you can do, if you really want to do it that way. I suggest you have a denormalized table and store your vals there
即使我不赞成这样保存数据,但如果您真的想这样做,您可以这样做。我建议你有一个非规范化的表并将你的 val 存储在那里
in your HTML you can have your checkboxes like this (considering you are storing ids of some sort)
在您的 HTML 中,您可以拥有这样的复选框(考虑到您正在存储某种类型的 ID)
<input type="checkbox" name="ids[]" value"1" />
<input type="checkbox" name="ids[]" value"24" />
<input type="checkbox" name="ids[]" value"56" />
<input type="checkbox" name="ids[]" value"100" />
On you php side you can use function implode to form ids into a string as shown below (considering you are doing a POST)
在您的 php 端,您可以使用函数 implode 将 ids 形成一个字符串,如下所示(考虑到您正在执行 POST)
$ids = implode(",",$_POST["ids"]);
Where you read from the database you can transform the value from db to an array like this
在从数据库读取的地方,您可以将值从 db 转换为这样的数组
$ids_array = explode(",",$row->ids);
I hope this helps
我希望这有帮助
回答by sri
first create database:
首先创建数据库:
create table employee(id int(10) not null, name varchar(20), hobbie varchar(20),
worked varchar(20), primary key(id));
after that create an html page like that:
之后创建一个这样的html页面:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1 /DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<body background="blue">
<form action="check.php" method="post">
Name: <input name="Name" type="text" id="Name" /><br />
<br />
<br />
Which you do you want to likes?<br />
<input type="checkbox" name="Hobbies[]" value="Books" />Books<br />
<input type="checkbox" name="Hobbies[]" value="Movies" />Movies<br />
<input type="checkbox" name="Hobbies[]" value="Sports" />Sports<br />
<input type="checkbox" name="Hobbies[]" value="Games" />Games<br />
<input type="checkbox" name="Hobbies[]" value="Travelling" />Travelling<br />
worked: <input name="Worked" type="text" id="Worked" /><br />
<br />
<input type="submit" name="submit" value="Submit" />
<input type="reset" name="reset" value="reset" />
</form>
</body>
</html>
after that we have do mysql connect.php
之后我们做了 mysql connect.php
<?php
$server="localhost";
$user="root";
$password="";
$database="empcheckbox";
$link=mysql_connect($server,$user,$password) or die("the connection is terminated please check me!".mysql_error());
mysql_select_db($database,$link);
?>
after that we have to create an check.php like that ok
之后我们必须创建一个 check.php 就可以了
<?php
if(isset($_POST['submit']))
{
$name=mysql_real_escape_string($_POST['Name']);
$worked=mysql_real_escape_string($_POST['Worked']);
$hobb= $_POST['Hobbies'];
if(empty($hobb))
{
echo("<p>You didn't select any any hobby.</p>\n");
}
else
{
$N = count($hobb);
echo("<p>You selected $N Hobbies(s): ");
for($i=0; $i < $N; $i++)
{
$var1=$hobb[$i];
include ('connect.php');
$table = "INSERT INTO employee (name, hobbies, worked) ".
"VALUES ('$name', '$var1', '$worked')";
mysql_query($table) or die(mysql_error());
$inserted_fid = mysql_insert_id();
mysql_close();
}
echo "successfully uploaded!..";
}
}
else
{
echo "error please check ur code";
}
回答by Alex Jose
The perfect solution for this is task the creation of normalized table as commented by @OMG and @Michael.
对此的完美解决方案是按照@OMG 和@Michael 的评论创建规范化表。
But here is the answer for what you just asked
但这是你刚才问的问题的答案
$ids = implode(", ", $_POST['ids']);
Store this in MySQL table. You can use LIKE command to query the table and use the explode to get back the ids in array.
将其存储在 MySQL 表中。您可以使用 LIKE 命令查询表并使用爆炸来取回数组中的 id。
$query = "SELECT * FROM <table> WHERE ids LIKE '%,2, %'"; // get posts having id 2
$id = explode(", ", $result->ids);
回答by Tango Bravo
You're going to want to go through the basics of PHP and MySQL.
您将需要了解 PHP 和 MySQL 的基础知识。
Check out tizag.com or w3schools.com, or some other sites (the tutorials are plentiful).
查看 tizag.com 或 w3schools.com,或其他一些网站(教程很多)。
Here's the basics though--and remember this, as it'll help you in your understanding.
不过,这是基础知识——记住这一点,因为它会帮助你理解。
MySQL is a database. A database is typically used for storing data. PHP is a programming language. It's typically used for programming.
MySQL是一个数据库。数据库通常用于存储数据。PHP 是一种编程语言。它通常用于编程。
So, some wonderful developers out there have already taken care of the steps for talking to the database from PHP. All you have to do is establish a connection.
因此,一些优秀的开发人员已经完成了从 PHP 与数据库对话的步骤。您所要做的就是建立连接。
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con) {
die('Could not connect: ' . mysql_error());
} else { echo "Connection made"; }
?>
See mysql_connect via W3Schools
Okay, so what you have done here, is you've connected to the database SERVER. You haven't selected a database yet. Think of it like going to a movie theater, you still have to pick a movie to watch.
好的,您在这里所做的就是连接到数据库 SERVER。您还没有选择数据库。把它想象成去电影院,你仍然必须选择一部电影来观看。
So, now we connect to our database:
所以,现在我们连接到我们的数据库:
mysql_select_db("my_db", $con); //Notice we're using our connection, "$con"
See mysql_select_db via W3Schools
Once you've connected to your database, you're ready to grab some information from it.
To do this, you need to create your SQL query.
连接到数据库后,您就可以从中获取一些信息了。
为此,您需要创建 SQL 查询。
Something to the tune of:
有点像:
$sql = "SELECT article_id FROM user_view_blog_posts WHERE user_id = '$user_id'";
See the SELECT statement via W3Schools
Depending on how your table is set up, that will get you the list for the current user. I'm assuming that you already have the user's id (or a way to get it), since they have the ability to define their own preferences for the site.
根据您的表的设置方式,这将为您提供当前用户的列表。我假设您已经拥有用户的 id(或获取它的方法),因为他们能够为网站定义自己的偏好。
Now that you have the SQL query to get the articles, you need to query the database.
现在您已经有了获取文章的 SQL 查询,您需要查询数据库。
$result = mysql_query($sql);
// Now, get the data
while($row = mysql_fetch_array($result)) {
$articles[] = $row['article_id'];
}
That should get you your list of ID's that you need.
这应该会为您提供所需的 ID 列表。
I'll let you figure out the rest. It's pretty straight-forward, and you've got all of the tools that you need now. The only thing you might want to brush up on is explode
and foreach
.
我会让你弄清楚剩下的。这非常简单,您已经拥有了现在需要的所有工具。您可能唯一想复习的是explode
和foreach
。
So, the way you store them is up to you. Look into explode for splitting them up when they're stored that way.
因此,您存储它们的方式取决于您。当它们以这种方式存储时,请查看爆炸以将它们分开。