下面是我的代码。我有两个MySQL数据库表,一个是“成员”,另一个是“参与者”。我想将表“member”中的数据显示到我的本地主机页,我做到了。但是,我无法使用复选框将多行“成员”数据插入到数据库表“参与者”中。我被卡住了。非常感谢您的帮助。
<?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(); } ?>
您没有在insert[]数组中存储$Name和$difficia值,只存储$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 = ''; }