PHP:如何从数据库中获取相同 ID 的多个复选框值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18569233/
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
PHP: How to get multiple checkbox values from database for same ID?
提问by Sam
I am new to php & need little help here. I've following code to INSERT multiple checkbox values into a table for same ID:
我是 php 的新手,在这里几乎不需要帮助。我使用以下代码将多个复选框值插入到相同 ID 的表中:
on my form I have:
在我的表格上,我有:
<input type="checkbox" name="subcat[]" value="Mech">Mech
<input type="checkbox" name="subcat[]" value="Ele">Ele
<input type="checkbox" name="subcat[]" value="Civ">Civ
<input type="checkbox" name="subcat[]" value="Air">Air
<input type="checkbox" name="subcat[]" value="BSL">BSL
I've checked "Mech", "Ele" and "BSL"
我检查过“Mech”、“Ele”和“BSL”
and PHP to insert:
和 PHP 插入:
$subcat = $_POST['subcat'];
for($i=0; $i<sizeof($subcat);$i++){
$sql1="INSERT INTO mst_scatadd (party_code,scid)
VALUES ('$pcode',$subcat[$i])";
mysql_query($sql1,$con);
}
db looks something like...
db 看起来像...
sctid | party_code | scid
---------------------------------
1 | 01S001 | Mech
2 | 01S001 | Ele
3 | 01S001 | BSL
4 | 01K207 | Main
Now, how can I retrieve these values from db to my form for the same ID and make them as checked if I want to edit the checkboxes?
现在,如果我想编辑复选框,如何将这些值从 db 检索到我的表单中的相同 ID 并使其处于选中状态?
Little help would be appreciated!!
一点帮助将不胜感激!
Thanks in adv.
感谢广告。
EDIT 1:
编辑 1:
Hello again guys!
大家好!
I've done with inserting and retrieving checkbox values using implode and explode and its working fine. Thanks to @Antoniossss for good suggession to keep checkboxes values as numbers(make sure the column in db should be VARCHAR) Thanks to @Barmar to explain use of explode & thanks to @MarkTWebsite to share idea of if-else
我已经使用内爆和爆炸完成了插入和检索复选框值的工作,并且工作正常。感谢@Antoniossss 提供了将复选框值保留为数字的良好建议(确保 db 中的列应该是 VARCHAR)感谢@Barmar 解释了explode的使用以及感谢@MarkTWebsite 分享了 if-else 的想法
Code for inserting multiple checkbox values:
插入多个复选框值的代码:
foreach ($_POST['subcat'] as $_subcat)
{
$checksub[] = $_subcat;
} $finalsub = implode(',', $checksub);
$sql="INSERT INTO vendor_mst(party_code, subcat) VALUES ('$pcode','$finalsub')";
My final code to retrieve checkbox values from db...
我从数据库中检索复选框值的最终代码...
sql="SELECT * FROM vendor_mst WHERE party_code like '".$searchname."'";
$result=mysql_query($sql,$con);
while ($row=mysql_fetch_array($result, MYSQL_BOTH)){
$checksub = explode(',',$row['subcat']);
}
if(in_array("1",$checksub))echo '<input type="checkbox" name="subcat[]" value="1" checked >Mech'; else echo '<input type="checkbox" name="subcat[]" value="1">Mech';
if(in_array("2",$checksub))echo '<input type="checkbox" name="subcat[]" value="2" checked >Ele'; else echo '<input type="checkbox" name="subcat[]" value="2">Ele';
if(in_array("3",$checksub))echo '<input type="checkbox" name="subcat[]" value="3" checked >Civ'; else echo '<input type="checkbox" name="subcat[]" value="3">Civ';
if(in_array("4",$checksub))echo '<input type="checkbox" name="subcat[]" value="4" checked >Air'; else echo '<input type="checkbox" name="subcat[]" value="4">Air';
if(in_array("5",$checksub))echo '<input type="checkbox" name="subcat[]" value="5" checked >BSL'; else echo '<input type="checkbox" name="subcat[]" value="5">BSL';
Thanks to stackoverflow!
感谢stackoverflow!
回答by Antoniossss
I would rather go in direction of threating checkboxes as binary flags and store their binary OR operation into DB as integer. It is really easy to implement, and will simplify record relations in your database. To do that you need to change values of checkboxes into 2^n values. For example
我宁愿将复选框作为二进制标志进行威胁,并将它们的二进制 OR 运算作为整数存储到 DB 中。它真的很容易实现,并且会简化数据库中的记录关系。为此,您需要将复选框的值更改为 2^n 个值。例如
<input type="checkbox" name="subcat[]" value="1">Mech
<input type="checkbox" name="subcat[]" value="2">Ele
<input type="checkbox" name="subcat[]" value="4">Civ
<input type="checkbox" name="subcat[]" value="8">Air
<input type="checkbox" name="subcat[]" value="16">BSL
selecting Mech
and Civ
should be storen in DB as 5 (binary 00101), Air
+BSL
would be 24 (11000b) and so on. To revert this process you would just simply test every bit of stored value and check/uncheck corresponding boxes in loop. I hope that you will get my point.
选择Mech
并Civ
应存储在 DB 中为 5(二进制 00101),Air
+BSL
将是 24(11000b),依此类推。要恢复此过程,您只需简单地测试存储值的每一位并在循环中选中/取消选中相应的框。我希望你能明白我的意思。
EDIT: example code as requested. Be aware that I AM NOTa PHP programmer so there could (and definetly will be) syntax errors but I will do my best To get user input you have to simply add values of checked boxes
编辑:根据要求的示例代码。请注意,我不是PHP 程序员,因此可能(并且肯定会)出现语法错误,但我会尽力获取用户输入,您必须简单地添加复选框的值
$selected=0;
foreach($POST['subcat'] as $checkedBox){
$selected=$selected+$checkedBox
}
So now variable $selected
will have encoded status of all checkboxes
To check which boxes (I never have troubles with that word) should be check or not you have to test every bit of stored value in DB. I dont know how are you generating your view, so i will provide only a template, you have to figure it out how to apply it to your project
所以现在变量$selected
将具有所有复选框的编码状态要检查哪些框(我从来没有遇到过这个词的问题)是否应该检查,您必须测试数据库中存储值的每一位。我不知道你是如何生成视图的,所以我只提供一个模板,你必须弄清楚如何将它应用到你的项目中
$valueFromDb= /// some value fetched from DB
$maxValue= //// the highest value of your checkboxes, in my eg. 16
for($testValue=1;$testValue<=$limit;$testValue=$testValue << 1){
$result=($valueFromDb & $testValue) > 0;
// do something with checked result for current checkbox
}
variable result
above will have checked
status (boolean value) of coresponding checkboxes. Each loop iteration coresponds to different checkbox in order from Mech to BSL one by one.
Alternatively you can print checkboxes directly and set them as checked with if
inscruction
$valueFromDb= // fetched value
result
上面的变量将具有checked
相应复选框的状态(布尔值)。每次循环迭代从Mech到BSL依次对应不同的checkbox。或者,您可以直接打印复选框并将它们设置为已选中,if
并使用 $valueFromDb= // fetched value
<input type="checkbox" name="subcat[]" value="1" <?php if($valueFromDb & 1 >0) echo('checked') ?php>Mech
<input type="checkbox" name="subcat[]" value="2" <?php if($valueFromDb & 2 >0) echo('checked') ?php>>Ele
<input type="checkbox" name="subcat[]" value="4" <?php if($valueFromDb & 4 >0) echo('checked') ?php>>Civ
.... and so on and on and on
I have just noticed that combining those 2 methods would result in generating checboxes dynamicly in loop so the code will be much more readable. All you would need is to provide map of checbox value labels:) I hope that eg. above will definetlly clearify how to apply such solution.
我刚刚注意到结合这两种方法会导致在循环中动态生成复选框,因此代码将更具可读性。您只需要提供复选框值标签的地图:) 我希望例如。以上将明确说明如何应用此类解决方案。
回答by user777388
<?php
$checksub = array('1','2','3');
?>
<form action="<?php echo site_url('index/do_upload') ?>" method="post" enctype="multipart/form-data">
<label>Select file : <input type="file" name="userfile"></label>
<input type="submit" name="action">
<input type="checkbox" name="subcat[]" value="1" <?php if (in_array(1,$checksub)){ echo "checked"; }?>/>
</form>
回答by MarkTWebsite
You will need to use the PHP if statement; I don't really understand your db structure, else I would provide code however, if you use PHP if, for each checkbox, check in the database to see if it's selected then; if it is selected
您将需要使用 PHP if 语句;我不太了解您的数据库结构,否则我会提供代码,但是,如果您使用 PHP,如果对于每个复选框,请检查数据库以查看它是否被选中;如果它被选中
echo '<input type="checkbox" name="subcat[]" value="Mech" selected>Mech';
else;
别的;
echo '<input type="checkbox" name="subcat[]" value="Mech">Mech';
Do you understand what I mean?
你明白我的意思吗?
Source; HTML/CSS/PHP Developer for 3 years.
来源; HTML/CSS/PHP 开发人员 3 年。
回答by Barmar
You can retrieve the subcats with:
您可以使用以下方法检索子猫:
SELECT party_code, GROUP_CONCAT(scid) scids
FROM mst_scadd
GROUP BY party_code
Then when you're fetching the rows from the database, you can do:
然后,当您从数据库中获取行时,您可以执行以下操作:
$scids = array_flip(explode(',', $row['scids']));
That will create an associative array whose keys are the subcategories. Then your code for displaying the checkboxes can be something like:
这将创建一个关联数组,其键是子类别。然后你的显示复选框的代码可以是这样的:
foreach ($all_subcats as $sc) {
echo '<input type="checkbox" name="subcat[]" value="' . $sc . '" ' .
(isset($scids[$sc]) ? 'checked' : '') . '>' . $sc;
}