这就是我已经改变它,仍然没有 - 没有错误,运行$ _POST并且不会插入任何东西。
$sql = "INSERT INTO appts (trainer, date, time, name, phone, club, group_key) values (?, ?, ?, ?, ?, ?, ?)";
$q = $db->prepare($sql);
$q->execute(array($train, $_POST['date'], $time, $_POST['name'][$i], $_POST['phone'][$i], $club, $group_key));
我最近切换到PDO,因为我终于升级了我的托管,并且我在尝试从一个表单中插入多行到我的数据库时遇到问题。如果有人能看到我做错了什么,我将不胜感激!
代码尝试做什么:客户端数量的表单 - >循环以生成一组输入,其数量等于刚输入的客户端数量 - >将所有这些插入到数据库中(时间仅放入第一个,其他时间留空)
if($action == 'group'){
echo "Number of clients: <form method='post'><input type='text' name='num' value='$_POST[num]'><input type='submit' value='Go' name='group'></form>";
if($_POST['group']){
$num = $_POST['num'];
?>
<form method='post'>
<br>
<table>
<tr>
<td>Time:</td>
<td><input type='text' name='time'></td>
</tr>
<tr>
<?
if(!$trainer){
$q = $db->prepare("SELECT name from trainers where club = '$club'");
$q->execute();
echo "<td>Trainer:</td> <td><select name='trainer'><option value=''></option>";
while($row = $q->fetch()){
echo "<option value='$row[id]'>$row[name]</option>";
}
echo "</select></td>";
}
for($i = 1; $i < $_POST['num'] +1; $i++){
echo "
<tr>
<td>Name $i: </td>
<td><input type='text' name='name[]'>
</tr>
<tr>
<td> Phone:</td>
<td><input type='text' name='phone[]'></td>
</tr>
<tr><td><br></td></tr>
";
}
?>
</table>
<input type='submit' name='addgroup'>
</form>
<?
if($_POST['addgroup']){
$group_key = substr(md5(microtime()),rand(0,26),5);
for($i = 0; $i < sizeof($_POST['name']); $i++){
$time = '';
if($i = 0){
$time = $_POST['time'];
}
if($trainer){
$train = $trainer;
}
else{
$train = $_POST['trainer'];
}
$sql = "INSERT INTO appts SET trainer = ?, date = ?, time = ?, name = ?, phone = ?, club = ?, group_key = '$group_key'";
$q = $db->prepare($sql);
$q->execute(array($train, $_POST['date'], $time, $_POST['name'][$i], $_POST['phone'][$i], $club));
}
}
}
答案 0 :(得分:1)
您的插入查询看起来不正确。请尝试以下方法:
$sql = "INSERT INTO appts (trainer, date, time, name, phone, club, group_key) values (?, ?, ?, ?, ?, ?, '$group_key')";
您还应该将$group_key
中的array
移动到execute
方法。不知道为什么你在$sql
中拥有它,所以我保持原样。
答案 1 :(得分:0)
你的SQL查询不好。
INSERT INTO appts (trainer, etc) VALUES (?,?)
或
UPDATE appts SET trainer = ? WHERE something = ?
答案 2 :(得分:-1)
我最终逐步重建打印结果以查看打破的位置。我有if($i = 0)
应该是if($i == 0)
(duh)。总是小事。以下是我最终使用的内容:
if($_POST['addgroup']){
$group_key = substr(md5(microtime()),rand(0,26),5);
if(!isset($_GET['trainer'])){
$train = $_POST['trainer'];
}
else{
$train = $_GET['trainer'];
}
for($i = 0; $i < count($_POST['name']); $i++){
$time = '';
if($i == 0){
$time = $_POST['time'];
}
$data = array($train, $date, $time, $_POST['name'][$i], $_POST['phone'][$i], $club, $group_key);
$sql = "INSERT INTO appts (trainer, date, time, name, phone, club, group_key) VALUES (?, ?, ?, ?, ?, ?, ?)";
$q = $db->prepare($sql);
$q->execute($data);
echo "<pre>";
print_r($data);
echo "</pre>";
}
}