gpt4 book ai didi

php - 使用复选框将多行插入MySQL

转载 作者:行者123 更新时间:2023-11-29 03:19:24 27 4
gpt4 key购买 nike

下面是我的代码。我有两个 MySQL 数据库表,一个是“成员”,另一个是“参与者”。我想将表“成员”中的数据显示到我的本地主机页面,我做到了。但是,我无法通过对数据库表“参与者”使用复选框来插入多行“成员”数据。我卡住了。任何帮助深表感谢。

<?php
try {
$con = new PDO("mysql:host=localhost;dbname=kgruum member", "root", "");
$sql = $con->query("SELECT * FROM member");
echo "<table class='info' align='center' border='1'>";
echo "<tr><td width='10'></td>
<td width='10'><b>ID</b></td>
<td width='500'><b>Name</b></td>
<td width='50'><b>Handicap</b></td><tr>";

foreach($sql as $row) {
$ID = $row["ID"];
$Name = $row["Name"];
$Handicap = $row["Handicap"];
echo "<tr>
<td><form method='POST' action='Add participant.php'><input type='checkbox' name='insert[]' value='$ID'></td>
<td>$ID</td>
<td>$Name</td>
<td>$Handicap</td><tr>";
}

echo"</table><div align='center'><input type='image' value='submit' src='add selected button.png' alt='submit Button' onmouseover='this.src='pink add selected button.png'' onmouseout='this.src='add selected button.png'' name='add_btn' id='add_btn'></div><br></form>";


if(isset($_POST['add_btn'])) {
if(!empty($_POST['insert'])) {
foreach($_POST['insert'] as $check) {
$st=$con->prepare("INSERT INTO participants(ID,Name,Handicap) VALUES('$ID','$Name','$Handicap')");
$insert->bindParam('ID',$ID);
$insert->bindParam('Name',$Name);
$insert->bindParam('Handicap',$Handicap);
$st->execute();
}
echo "<script type='text/javascript'>
alert('Successful Insert ! ');
window.location.href = 'Add participant.php';
</script>";
} else {
echo "<script type='text/javascript'>alert('You didn't choose which user you want to insert ! ')</script>";
}
}
} catch(PDOException $e) {
echo "error".$e->getMessage();
}
?>

最佳答案

您没有将 $Name 和 $Handicap 值存储在 insert[] 数组中,您只存储了 $ID 值。

要解决,请执行以下操作:

<input type='checkbox' name='insert[]' value='$ID|$Name|$Handicap'>

然后:

foreach($_POST['insert'] as $check) {
$values = explode('|', $check);
$ID = $values[0];
$Name = $values[1];
$Handicap = $values[2];
//The rest of your SQL code goes here as you have it...
$check = '';
}

关于php - 使用复选框将多行插入MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47791859/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com