我试图在数据库中插入用户答案(到php表单)。 答案将插入到“答案”表中,该表有4列:(Id,userId,qId,answer)其中Id是唯一ID,qId是问题Id(问题存储在表“问题”中)。
问题: 这是我尝试将数据插入数据库的代码(insertPage1.php):
<?php
try{
$conn = new PDO('mysql:dbname=Application;host=localhost;charset=utf8mb4', 'user', 'xxxx');
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$i = 0;
foreach($_SESSION['post'] as $key => $value) {
$stmt = $conn->prepare('INSERT INTO Answer (userId, qId, answer) VALUES (userId = :username, qId = :qId, answer = :answer)');
$stmt -> execute(array(':username' => $_SESSION['SESS_USERNAME'], ':qId' => $key, ':answer' => $value));
echo "$i\n";
echo "$key\n";
echo "$value\n";
$i++;
}
}
catch(PDOException $e) {
echo 'Exception -> ';
var_dump($e->getMessage());
}
?>
这是page2.php中的代码,我在第1页检查发布的答案:
foreach ($_POST as $key => $value) {
if (is_array($_POST[$key])){
$_SESSION['post'][$key] = implode("\n", $_POST[$key]);
}
else{
$_SESSION['post'][$key] = $value;
}
}
extract($_SESSION['post']); // Function to extract array.*/
include('insertPage1.php');
?>
<html>
//html for the second page...
</html>
,结果如下:|
但重点是,在第一个代码“insertPage1.php”中可以看到,我添加了3行(echo)来打印$ i,$ key和$ value的值......虽然,我看到了$ value在日志中正确显示(即显示q1,q2,...),我不知道为什么它们在表中显示为“0”?!!!
任何想法都会受到高度赞赏,
答案 0 :(得分:2)
userId
是您为自己的专栏提供的名称,请勿使用用户名,这只会让您感到困惑$_SESSION['userId']
并使用session_start()
。$_POST
!
try{
$conn = new PDO('mysql:dbname=Application;host=localhost;charset=utf8mb4', 'user', 'xxxx');
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = 'INSERT INTO Answer (userId, qId, answer) VALUES (:userId, :qId, :answer)';
$stmt = $conn->prepare($sql);
foreach ($_POST as $key => $value) {
if (!is_array($_POST[$key])){
$stmt->execute(array(':userId' => $_SESSION['userId'], ':qId' => $key, ':answer' => $value));
}
else{
foreach ($_POST[$key] as $sub_key => $sub_value) {
$stmt->execute(array(':userId' => $_SESSION['userId'], ':qId' => $sub_key, ':answer' => $sub_value));
}
}
}
}
catch(PDOException $e) {
echo 'Exception -> ';
var_dump($e->getMessage());
}
一些调试提示:
0
相当于int print_r($_POST)
或print_r($_SESSION)
error_log
很有帮助,用它来记录您要插入的变量答案 1 :(得分:1)
更正此声明
$stmt = $conn->prepare('INSERT INTO Answer (userId, qId, answer) VALUES (userId = :username, qId = :qId, answer = :answer)');
到
$stmt = $conn->prepare('INSERT INTO Answer (userId, qId, answer) VALUES (:username, :qId, :answer)');