php 如何使用php将多个复选框值插入到数据库中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23292983/
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
how insert the multiple checkbox values into database using php
提问by user3422452
By this code i can able insert the checkbox values to database. But i need add one column in phpmyadmin and in that column i need store the values like, if i select 2 checkbox, i need store that ckeckbox values in one column in another column i need store for selected checkbox as YES and unselected values as NO. But see i want both column
通过此代码,我可以将复选框值插入数据库。但我需要在 phpmyadmin 中添加一列,在该列中我需要存储值,例如,如果我选择 2 个复选框,我需要将该 ckeckbox 值存储在另一列的一列中,我需要将选定的复选框存储为 YES,将未选择的值存储为 NO . 但看我想要两列
here is my code
这是我的代码
<input type="checkbox" name="checkbox[]" value="Home" id="pageHome" onChange="toggleVisibility('home');" /><label for="pageHome"> Home</label><img id="home" src="images/icon-tick.png" style="visibility:hidden"/><br/>
<input name="checkbox[]" value="About_us" id="page_Aboutus" type="checkbox" onChange="toggleVisibility('aboutus');"><label for="page_Aboutus"> About Us</label><img id="aboutus" src="images/icon-tick.png" style="visibility:hidden" /><br/>
<input name="checkbox[]" value="Services" id="pageServices" type="checkbox" onChange="toggleVisibility('services');"><label for="pageServices"> Services</label><img id="services" src="images/icon-tick.png" style="visibility:hidden" /><br/>
<input name="checkbox[]" value="Products" id="pageProducts" type="checkbox" onChange="toggleVisibility('products');"><label for="pageProducts"> Products</label><img id="products" src="images/icon-tick.png" style="visibility:hidden"/><br/><br>
<input name="checkbox[]" value="Enquiry" id="pageEnquiry" type="checkbox" onChange="toggleVisibility('enquiry');"><label for="pageEnquiry"> Enquiry</label><img id="enquiry" src="images/icon-tick.png" style="visibility:hidden"/><br/><br>
<input name="checkbox[]" value="Contact_us" id="pageContact" type="checkbox" onChange="toggleVisibility('Contact');"><label for="pageContact">Contact Us</label><img id="Contact" src="images/icon-tick.png" style="visibility:hidden" /><br/>
php code
代码
$required_pages = implode(',', $_REQUEST['checkBox']);
$sql="insert into request_quote(customer_name,organisation,phone_num,email,country,state,city,zipcode,project_type,website_url,website_purpose,website_keyword,Competitors,sample_websites,no_of_updation,required_pages,additional_page,other_details)
values('$customer_name','$organisation','$phone_num','$email','$country','$state','$city','$zipcode','$project_type','$website_url','$website_purpose','$website_keyword','$Competitors','$sample_websites','$no_of_updation','$required_pages','$additional_page','$other_details')";
mysql_query($sql) or die(mysql_error());
回答by Andreas Storvik Strauman
You can add a value='YES'
attribute to each of your checkboxes.
Then make an array where you assume no checkbox has been checked. Because when we iterate later, only the checked checkboxes will be sent via $_REQUEST
.
您可以value='YES'
为每个复选框添加一个属性。然后创建一个数组,您假设没有选中任何复选框。因为当我们稍后迭代时,只有选中的复选框才会通过$_REQUEST
.
$checkBoxes['customer_name']="NO";
$checkBoxes['organisation']="NO";
$checkBoxes['phone_num']="NO";
$checkBoxes['email']="NO";
$checkBoxes['country']="NO";
$checkBoxes['state']="NO";
$checkBoxes['city']="NO";
$checkBoxes['zipcode']="NO";
$checkBoxes['project_type']="NO";
$checkBoxes['website_url']="NO";
$checkBoxes['website_purpose']="NO";
$checkBoxes['website_keyword']="NO";
$checkBoxes['Competitors']="NO";
$checkBoxes['sample_websites']="NO";
$checkBoxes['no_of_updation']="NO";
$checkBoxes['required_pages']="NO";
$checkBoxes['additional_page']="NO";
$checkBoxes['other_details']="NO";
// Only the checked checkboxes wil be itterated below.
// This will mean the $value would be YES no matter what.
// So I write it literal for SQL-Injection-security
foreach ($_REQUEST['checkbox'] as $checkboxName=>$value){
$checkBoxes[$checkBoxName]="YES";
}
And in your SQL-Query, replace the variables with items from the array. I.E.
在您的 SQL-Query 中,用数组中的项目替换变量。IE
$sql="insert into request_quote(customer_name)
values('".$checkBoxes['customer_name']."')";
Security tip:
安全提示:
Also, directly inserting user input can be a huge security risk. Use mysql_real_escape_string($value)
on all user-input-values you plan to use in a SQL-query.
此外,直接插入用户输入可能存在巨大的安全风险。用于mysql_real_escape_string($value)
您计划在 SQL 查询中使用的所有用户输入值。
You should look into $_POST. W3Schools will help you out: http://www.w3schools.com/php/php_forms.asp.
您应该查看 $_POST。W3Schools 将帮助您:http: //www.w3schools.com/php/php_forms.asp。
回答by Junior
You have to use 3 tables, and relationate each other
您必须使用 3 个表,并相互关联
table 1 -> customers (id, name, etc)
table 2 -> required_pages (id, name)
- here you will add your options from checkbox (Home, About_us, etc)table 3 -> customers_required_pages (id, customer_id, required_page_id)
table 1 -> customers (id, name, etc)
table 2 -> required_pages (id, name)
- 在这里,您将从复选框中添加您的选项(主页、About_us 等)table 3 -> customers_required_pages (id, customer_id, required_page_id)
When saving data, you will have to save sequentialy:
保存数据时,您必须按顺序保存:
Your customer:
$sql = "INSERT INTO customers (field1, field2, fieldn...)" $qry = mysql_query($sql);
Retrieve your customer Id:
$sql = "SELECT LAST_INSERT_ID() AS customerId"; $qry = mysql_query($sql); $customerId = mysql_fetch_assoc($qry);
Save the relationship between customers and required_pages
<?php foreach ($_REQUEST['checkBox'] as $oneCheckbox => $checkboxValue) { $sql = "INSERT INTO customers_required_pages (customer_id, required_page_id) VALUES ({$customerId['customerId']}, '{$checkboxValue}')"; } ?>
When retrieving your data, you will select values from table2 using left join with table3, this way you will be able to know wich values where or not selected from the checkbox list
$sql = "SELECT rp.id, rp.name, IF(crp.customer_id IS NULL, 'NO', 'YES') AS checked FROM required_pages rp LEFT JOIN customers_required_pages crp ON rp.id = crp.required_page_id";
您的客户:
$sql = "INSERT INTO customers (field1, field2, fieldn...)" $qry = mysql_query($sql);
检索您的客户 ID:
$sql = "SELECT LAST_INSERT_ID() AS customerId"; $qry = mysql_query($sql); $customerId = mysql_fetch_assoc($qry);
保存customers和required_pages的关系
<?php foreach ($_REQUEST['checkBox'] as $oneCheckbox => $checkboxValue) { $sql = "INSERT INTO customers_required_pages (customer_id, required_page_id) VALUES ({$customerId['customerId']}, '{$checkboxValue}')"; } ?>
检索数据时,您将使用左连接与 table3 从 table2 中选择值,这样您就可以知道从复选框列表中选择或未选择的值
$sql = "SELECT rp.id, rp.name, IF(crp.customer_id IS NULL, 'NO', 'YES') AS checked FROM required_pages rp LEFT JOIN customers_required_pages crp ON rp.id = crp.required_page_id";
As an extra, consider use MySQLi or PDO instead of mysql as your database library, since the use of mysql lib has been discouraged
另外,考虑使用 MySQLi 或 PDO 而不是 mysql 作为您的数据库库,因为不鼓励使用 mysql lib
回答by user2949229
I was having the problem to store the multiple checkbox into the mysql table, but now it's working fine with this code:
我在将多个复选框存储到 mysql 表中时遇到了问题,但现在使用此代码可以正常工作:
<html>
<head>
<title>Registration Page</title>
</head>
<body>
<?php
require("config.php");
?>
<?php
if(isset($_POST['submit'])){
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$gender = $_POST['gender'];
$hobbies = implode(",",$_POST['hobbies']);
echo $hobbies;
$country = $_POST['country'];
// echo $hobbies;
//foreach($hobbies as $hobbies1){
//echo $hobbies1;
//$implode = implode(',',$hobbies1);
$sql = "INSERT INTO `userinfo`(`fname`,`lname`,`gender`,`hobbies`,`country`)
values('$fname','$lname','$gender','$hobbies','$country')";
//}
//$sql = "INSERT INTO `userinfo`(`fname`,`lname`,`gender`,`hobbies`,`country`)
// values('$fname','$lname','$gender','$hobbies1','$country')";
$query = mysql_query($sql) or die(mysql_error());
if
($query){
echo "<h1>Data inserted .. Happy coding</h1>";
}else{
echo "<h1>Please check the problem</h1>";
}
}
//}
?>
<form name="registration" method="post" action="">
<table border="1" cellpadding="2" cellspacing="2" align="center">
<tr>
<td>First Name:</td><td><input type="text" name="fname" required=""></td>
</tr>
<tr>
<td>Last Name:</td><td><input type="text" name="lname" required=""></td>
</tr>
<tr>
<td>Gender:</td><td><input type="radio" name="gender" value="male" required="">Male <input type="radio" name="gender" value="female" >Female</td>
</tr>
<tr>
<td>Hobbies:</td><td><input type="checkbox" name="hobbies[]" value="tennis">Tennis <br>
<input type="checkbox" name="hobbies[]" value="cricket">Cricket <br>
<input type="checkbox" name="hobbies[]" value="dance">Dance7 <br>
<input type="checkbox" name="hobbies[]" value="sketching">Sketching
</td>
</tr>
<tr>
<td>Country:</td>
<td>
<select name="country">
<option >----select----</option>
<option>India</option>
<option>Pakistan</option>
<option>UAE</option>
</select>
</td>
</tr>
<tr>
<td><input type="submit" name="submit" value="Register me"></td>
</tr>
</table>
</form>
</body>
</html>