如何使用 php 将多个复选框选择添加到我的数据库
How to add multiple checkbox selections to my database using php
我有一个复选框输入,用于将活动插入到“sangamdb”数据库中“blooddonor”table的“act”列中。
但我似乎无法找出将表单中的多项选择插入数据库的正确方法table。
除此之外,其他元素工作正常。
到目前为止我的代码:
表格:
<form role="form" action = "addeddonor.php" method = "post">
<div class="form-group">
<label for="exampleInputEmail1">Activites</label><br>
<input type="checkbox" id="Football" name="act[]" value="Football">
<label for="Football">FootBall</label><br>
<input type="checkbox" id="Basketball" name="act[]" value="Basketball">
<label for="Basketball">BasketBall</label><br>
<input type="checkbox" id="Nattation" name="act[]" value="Nattation">
<label for="Nattation">Nattation</label><br>
<input type="checkbox" id="Karate" name="act[]" value="Karate">
<label for="Karate">Karate</label><br>
</div>
</div>
<div class="box-footer">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
PHP:(它不会将值插入数据库)
$checkBox = implode(',', $_POST['act']);
if(isset($_POST['submit']))
{
$query="INSERT INTO blooddonor (act) VALUES ('" . $checkBox . "')";
mysql_query($query) or die (mysql_error() );
echo "Complete";
}
if(isset($_POST['name'])){
$name = $_POST["name"];
$gender = $_POST["gender"];
$dob = $_POST["dob"];
$weight = $_POST["weight"];
$contact = $_POST["contact"];
$bloodtype = $_POST["bloodtype"];
$adress = $_POST["adress"];
include 'conn.php';
//code after connection is successfull
$qry = "insert into blooddonor(name,gender,dob,weight,contact,bloodtype,adress) values ('$name','$gender','$dob','$weight','$contact','$bloodtype','$adress')";
$result = mysqli_query($conn,$qry); //query executes
if(!$result){
echo"ERROR";
}else {
echo" <div style='text-align: center'><h1>ADDED SUCCESSFULLY</h1>";
echo" <a href='index.php' div style='text-align: center'><h3>Go Back</h3>";
}
}else{
echo"<h3>YOU ARE NOT AUTHORIZED TO REDIRECT THIS PAGE. GO BACK to <a href='index.php'> DASHBOARD </a></h3>";
}
数据库:
CREATE TABLE IF NOT EXISTS `blooddonor`
(
`id` int(11) NOT NULL,
`name` varchar(50) NOT NULL,
`gender` varchar(20) NOT NULL,
`dob` date NOT NULL,
`weight` int(5) NOT NULL,
`contact` int(10) NOT NULL,
`bloodtype` varchar(3) NOT NULL,
`adress` varchar(50) NOT NULL,
`act` varchar(50) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
复选框代表值列表。一个用户可以 select 多个复选框,这意味着对于每个用户记录,您可能有一个值列表。因此,您需要在数据库中添加另一个 table 来存储这些选项。事实上,您总共可能需要三个 table:献血者、活动、activities_per_donor。有关详细信息,请参阅 What's the best way to store Checkbox Values in MySQL Database?
如何设计 table 取决于您,但您的 activities_per_donor 需要至少有两列:user_id 和 activity。您还应该在两列上创建复合主键以避免重复值。 activity 列应引用第三个 table 中的预定义活动列表,以便用户无法插入无效的 activity.
当您的表单被正确创建并且您的复选框被命名为数组(即 name="act[]"
)时,您将收到一个 selected 的数组$_POST['act']
变量中的 PHP 中的值。如果没有值被 selected 那么这个变量将不会被设置,所以你也需要检查它。您需要处理此数组并将每个元素作为新行插入 activities_per_donor table
如何使用 PDO 存储多个复选框
大多数时候您会使用 PDO 与数据库进行交互。要插入值,您需要执行准备好的语句。您需要将捐助者数据插入一个 table 并将他们的活动插入另一个,这需要您将两个插入都包装在一个事务中。
$pdo = new \PDO("mysql:host=localhost;dbname=test;charset=utf8mb4", 'user', 'password', [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_EMULATE_PREPARES => false
]);
if (isset($_POST["name"], $_POST["gender"], $_POST["dob"], $_POST["weight"], $_POST["contact"], $_POST["bloodtype"], $_POST["adress"])) {
$pdo->beginTransaction();
// Insert blood donor
$stmt = $pdo->prepare('INSERT INTO blooddonor(name,gender,dob,weight,contact,bloodtype,adress) VALUES (?,?,?,?,?,?,?)');
$stmt->execute([
$_POST["name"],
$_POST["gender"],
$_POST["dob"],
$_POST["weight"],
$_POST["contact"],
$_POST["bloodtype"],
$_POST["adress"],
]);
$donor_id = $pdo->lastInsertId();
// Insert donor's acitvities
if(isset($_POST['act'])) {
$stmt = $pdo->prepare('INSERT INTO activities_per_donor(donor_id, activity) VALUES (?,?)');
$stmt->bindValue(1, $donor_id);
$stmt->bindParam(2, $activity);
foreach ($_POST['act'] as $activity) {
$stmt->execute();
}
}
$pdo->commit();
}
如何使用 mysqli 存储多个复选框
如果您必须使用 mysqli,您仍然可以使用非常相似的代码实现相同的目的。再一次,我们启动一个事务并执行 2 个准备好的语句,然后将其提交到数据库中。
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'user', 'password', 'test');
$mysqli->set_charset('utf8mb4'); // always set the charset
if (isset($_POST["name"], $_POST["gender"], $_POST["dob"], $_POST["weight"], $_POST["contact"], $_POST["bloodtype"], $_POST["adress"])) {
$mysqli->begin_transaction();
// Insert blood donor
$stmt = $mysqli->prepare('INSERT INTO blooddonor(name,gender,dob,weight,contact,bloodtype,adress) VALUES (?,?,?,?,?,?,?)');
$stmt->bind_param('sssssss', $_POST["name"], $_POST["gender"], $_POST["dob"], $_POST["weight"], $_POST["contact"], $_POST["bloodtype"], $_POST["adress"]);
$stmt->execute();
$donor_id = $mysqli->insert_id;
// Insert donor's acitvities
if(isset($_POST['act'])) {
$stmt = $mysqli->prepare('INSERT INTO activities_per_donor(donor_id, activity) VALUES (?,?)');
$stmt->bind_param('ss', $donor_id, $activity);
foreach ($_POST['act'] as $activity) {
$stmt->execute();
}
}
$mysqli->commit();
}
我有一个复选框输入,用于将活动插入到“sangamdb”数据库中“blooddonor”table的“act”列中。
但我似乎无法找出将表单中的多项选择插入数据库的正确方法table。
除此之外,其他元素工作正常。
到目前为止我的代码:
表格:
<form role="form" action = "addeddonor.php" method = "post">
<div class="form-group">
<label for="exampleInputEmail1">Activites</label><br>
<input type="checkbox" id="Football" name="act[]" value="Football">
<label for="Football">FootBall</label><br>
<input type="checkbox" id="Basketball" name="act[]" value="Basketball">
<label for="Basketball">BasketBall</label><br>
<input type="checkbox" id="Nattation" name="act[]" value="Nattation">
<label for="Nattation">Nattation</label><br>
<input type="checkbox" id="Karate" name="act[]" value="Karate">
<label for="Karate">Karate</label><br>
</div>
</div>
<div class="box-footer">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
PHP:(它不会将值插入数据库)
$checkBox = implode(',', $_POST['act']);
if(isset($_POST['submit']))
{
$query="INSERT INTO blooddonor (act) VALUES ('" . $checkBox . "')";
mysql_query($query) or die (mysql_error() );
echo "Complete";
}
if(isset($_POST['name'])){
$name = $_POST["name"];
$gender = $_POST["gender"];
$dob = $_POST["dob"];
$weight = $_POST["weight"];
$contact = $_POST["contact"];
$bloodtype = $_POST["bloodtype"];
$adress = $_POST["adress"];
include 'conn.php';
//code after connection is successfull
$qry = "insert into blooddonor(name,gender,dob,weight,contact,bloodtype,adress) values ('$name','$gender','$dob','$weight','$contact','$bloodtype','$adress')";
$result = mysqli_query($conn,$qry); //query executes
if(!$result){
echo"ERROR";
}else {
echo" <div style='text-align: center'><h1>ADDED SUCCESSFULLY</h1>";
echo" <a href='index.php' div style='text-align: center'><h3>Go Back</h3>";
}
}else{
echo"<h3>YOU ARE NOT AUTHORIZED TO REDIRECT THIS PAGE. GO BACK to <a href='index.php'> DASHBOARD </a></h3>";
}
数据库:
CREATE TABLE IF NOT EXISTS `blooddonor`
(
`id` int(11) NOT NULL,
`name` varchar(50) NOT NULL,
`gender` varchar(20) NOT NULL,
`dob` date NOT NULL,
`weight` int(5) NOT NULL,
`contact` int(10) NOT NULL,
`bloodtype` varchar(3) NOT NULL,
`adress` varchar(50) NOT NULL,
`act` varchar(50) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
复选框代表值列表。一个用户可以 select 多个复选框,这意味着对于每个用户记录,您可能有一个值列表。因此,您需要在数据库中添加另一个 table 来存储这些选项。事实上,您总共可能需要三个 table:献血者、活动、activities_per_donor。有关详细信息,请参阅 What's the best way to store Checkbox Values in MySQL Database?
如何设计 table 取决于您,但您的 activities_per_donor 需要至少有两列:user_id 和 activity。您还应该在两列上创建复合主键以避免重复值。 activity 列应引用第三个 table 中的预定义活动列表,以便用户无法插入无效的 activity.
当您的表单被正确创建并且您的复选框被命名为数组(即 name="act[]"
)时,您将收到一个 selected 的数组$_POST['act']
变量中的 PHP 中的值。如果没有值被 selected 那么这个变量将不会被设置,所以你也需要检查它。您需要处理此数组并将每个元素作为新行插入 activities_per_donor table
如何使用 PDO 存储多个复选框
大多数时候您会使用 PDO 与数据库进行交互。要插入值,您需要执行准备好的语句。您需要将捐助者数据插入一个 table 并将他们的活动插入另一个,这需要您将两个插入都包装在一个事务中。
$pdo = new \PDO("mysql:host=localhost;dbname=test;charset=utf8mb4", 'user', 'password', [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_EMULATE_PREPARES => false
]);
if (isset($_POST["name"], $_POST["gender"], $_POST["dob"], $_POST["weight"], $_POST["contact"], $_POST["bloodtype"], $_POST["adress"])) {
$pdo->beginTransaction();
// Insert blood donor
$stmt = $pdo->prepare('INSERT INTO blooddonor(name,gender,dob,weight,contact,bloodtype,adress) VALUES (?,?,?,?,?,?,?)');
$stmt->execute([
$_POST["name"],
$_POST["gender"],
$_POST["dob"],
$_POST["weight"],
$_POST["contact"],
$_POST["bloodtype"],
$_POST["adress"],
]);
$donor_id = $pdo->lastInsertId();
// Insert donor's acitvities
if(isset($_POST['act'])) {
$stmt = $pdo->prepare('INSERT INTO activities_per_donor(donor_id, activity) VALUES (?,?)');
$stmt->bindValue(1, $donor_id);
$stmt->bindParam(2, $activity);
foreach ($_POST['act'] as $activity) {
$stmt->execute();
}
}
$pdo->commit();
}
如何使用 mysqli 存储多个复选框
如果您必须使用 mysqli,您仍然可以使用非常相似的代码实现相同的目的。再一次,我们启动一个事务并执行 2 个准备好的语句,然后将其提交到数据库中。
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'user', 'password', 'test');
$mysqli->set_charset('utf8mb4'); // always set the charset
if (isset($_POST["name"], $_POST["gender"], $_POST["dob"], $_POST["weight"], $_POST["contact"], $_POST["bloodtype"], $_POST["adress"])) {
$mysqli->begin_transaction();
// Insert blood donor
$stmt = $mysqli->prepare('INSERT INTO blooddonor(name,gender,dob,weight,contact,bloodtype,adress) VALUES (?,?,?,?,?,?,?)');
$stmt->bind_param('sssssss', $_POST["name"], $_POST["gender"], $_POST["dob"], $_POST["weight"], $_POST["contact"], $_POST["bloodtype"], $_POST["adress"]);
$stmt->execute();
$donor_id = $mysqli->insert_id;
// Insert donor's acitvities
if(isset($_POST['act'])) {
$stmt = $mysqli->prepare('INSERT INTO activities_per_donor(donor_id, activity) VALUES (?,?)');
$stmt->bind_param('ss', $donor_id, $activity);
foreach ($_POST['act'] as $activity) {
$stmt->execute();
}
}
$mysqli->commit();
}