[英]Query Checklist and post multiple results to table in mysql
Hello guys im trying to post several checklist values to a single table in my database but it only takes one single value into the table... 大家好我试图将几个清单值发布到我的数据库中的单个表中,但它只需要一个值进入表中...
Im doing it like this: 我这样做:
The Form: 表格:
<?php foreach($users as $user): ?>
<input type="checkbox" name="tipoinsertos" value="<?= $user['tipoinsertom']; ?>"> <?= $user['tipoinsertom']; ?>
<?php endforeach; ?>
And this is my post form: 这是我的帖子:
$data = array('tipoinsertos' => $_POST['tipoinsertos']);
try {
$dbh = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "INSERT INTO barrasinternas ( tipoinsertos ) VALUES (:tipoinsertos )";
$sth = $dbh->prepare($query);
$sth->execute($data);
echo "¡Añadida Exitosamente!";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$dbh = null;
?>
check this prints: 检查这个打印:
http://imgur.com/a/WRhFd http://imgur.com/a/WRhFd
So I checked all 3 values but only one was in my table. 所以我检查了所有3个值,但只有一个在我的表中。
Firstly, use an array for your input name tipoinsertos[]
首先,使用数组作为输入名称
tipoinsertos[]
<input type="checkbox" name="tipoinsertos[]" ...
Then you don't show how you're getting $data
but you need to be iterating and executing that query somehow in a loop. 然后你不会显示你是如何获得
$data
但你需要在循环中以某种方式迭代并执行该查询。 Either by building it up into one big query of values, or by executing another statement with one value over and over. 通过将其构建为一个大的值查询,或者通过一次又一次地执行具有一个值的另一个语句。 Here's a possible solution :
这是一个可能的解决方案 :
<?php
$users = [
['tipoinsertom' => 'Jonatan'],
['tipoinsertom' => 'jeff'],
['tipoinsertom' => 'joe'],
];
?>
<form method="POST">
<?php foreach($users as $user): ?>
<input type="checkbox" name="tipoinsertos[]" value="<?= $user['tipoinsertom']; ?>"> <?= $user['tipoinsertom']; ?>
<?php endforeach; ?>
<input type="submit" value="Submit"/>
</form>
<?php
// returns an intance of PDO
// https://github.com/jpuck/qdbp
$dbh = require __DIR__.'/tipoin_Dxa05i_A.pdo.php';
if( !empty( $_POST['tipoinsertos'] ) ){
// prepare the query once
$query = "INSERT INTO barrasinternas (tipoinsertos ) VALUES (:tipoinsertos )";
$sth = $dbh->prepare($query);
// iterate through list
foreach($_POST['tipoinsertos'] as $tipoinsertos){
$sth->execute(['tipoinsertos' => $tipoinsertos]);
}
// success
echo "¡Añadida Exitosamente!";
$dbh = null;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.