我在尝试将多个值同时插入表中的同一列时遇到问题,
此代码显示一个表: 表格Ex:
-----------------------------
Name | Last Name | Points |
-----------------------------
Test | 185 | |
-----------------------------
Test1 | 185 | |
-----------------------------
Test2 | 185 | |
-----------------------------
useradmin ca为每个用户插入点,但是当我点击summint将所有这些值插入数据库时我会发一条消息(错误) PDO :: prepare()期望参数1是字符串,给定的数组 还有一个 致命错误:在非目标
上调用成员函数execute()任何想法为什么或如何修复?
<?php
require("coneccion.php");
if(!empty($_POST))
{
$query = "INSERT INTO points (sid, ais, spoints) values (1, 2, :spoints)";
$query = array(':spoints' => $_POST['spoints']);
try
{
$stmt = $db->prepare($query);
$stmt = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Error 1 " . $ex->getMessage());
}
$cid = $_SESSION['cid'];
header("Location: index.php?id=$cid");
die("Rendirecting to index.php?id=$cid");
}
else
{
$id = $_SESSION['cid'];
echo 'Course id: ' .$id ;
$sid = $_GET['id'];
$query = "SELECT DISTINCT s.studentid, s.fname, s.lname, a.assignmentpoints, s.courseid, a.courseid, a.duedate FROM students as s, assignments as a WHERE s.courseid = '$id' and s.courseid = a.courseid and a.assignmentid = '$sid' ";
try
{
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
die("Error 2" . $ex->getMessage());
}
$rowstudents = $stmt->fetchAll();
}
?>
<form action="index.php" method="post">
<table border=1>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Assignment Points</th>
<th>Student Points</th>
</tr>
<?php foreach($rowstudents as $row): ?>
<tr>
<th><?php echo '' . htmlentities($row['studentid'], ENT_QUOTES, 'UTF-8') . '';?></th>
<th><?php echo '' . htmlentities($row['fname'], ENT_QUOTES, 'UTF-8') . '';?></th>
<th><?php echo '' . htmlentities($row['lname'], ENT_QUOTES, 'UTF-8') . '';?></th>
<th><?php echo '' . htmlentities($row['assignmentpoints'], ENT_QUOTES, 'UTF-8') . '';?></th>
<th><input type="text" name="spoints" value=""></th>
</tr>
<?php endforeach; ?>
</table>
<input type="submit" value="Submit">
</form>
答案 0 :(得分:2)
您在此处重新分配$query
:
$query = "INSERT INTO points (sid, ais, spoints) values (1, 2, :spoints)";
$query = array(':spoints' => $_POST['spoints']);
因此,在第二行之后,$query
变成一个包含一个元素的数组。
我认为你打算这样做:
$query = "INSERT INTO points (sid, ais, spoints) values (1, 2, :spoints)";
try
{
$stmt = $db->prepare($query);
$stmt->bindParam(':spoints', $_POST['spoints']);
$stmt->execute();
}
参考:http://us3.php.net/pdo.prepared-statements
此外,要获得多个点,请更改您的html元素:
<input type="text" name="spoints" value="">
到
<input type="text" name="spoints[]" value="">
注意带有数组spoints[]
的名称。发布后,$_POST['spoints']
将是一个可循环播放的数组并使用。
$points = null;
$query = "INSERT INTO points (sid, ais, spoints) values (1, 2, :spoints)";
try
{
$stmt = $db->prepare($query);
$stmt->bindParam(':spoints', $points);
foreach($_POST['spoints'] as $value) {
$points = $value;
$stmt->execute();
}
}
catch(PDOException $ex)
{
die("Error 1 " . $ex->getMessage());
}