php - SQL 未使用 PHP 插入
问题描述
我有以下代码将数据从表单发送到 SQL 数据库:
<?php
session_start();
ob_start();
include 'includes/db_connection.php';
if(empty($_POST)){
header("Location: index.php");
}
else{
try {
$dbconn = OpenCon();
$fname = $_POST['fnameInput'];
$sname = $_POST['snameInput'];
$sex = $_POST['sexInput'];
$dob = $_POST['dobInput'];
$schoolID = $_SESSION['school'];
$sqlstmnt2 = 'INSERT INTO students (`firstName`, `surname`, `dob`, `gender`, `schoolID`) VALUES (:firstName, :surname, :dob, :gender, :schoolID)';
$stmtUsr2 = $dbconn -> prepare($sqlstmnt2);
$stmtUsr2 -> bindValue(':firstName', $fname);
$stmtUsr2 -> bindValue(':surname', $sname);
$stmtUsr2 -> bindValue(':dob', $dob);
$stmtUsr2 -> bindValue(':gender', $sex);
$stmtUsr2 -> bindValue(':schoolID', $schoolID);
$stmtUsr2 -> execute();
// redirect to pupil's profile
header("Location: pupilprofile.php");
die();
}
catch (PDOException $e) {
echo "DataBase Error: The user could not be added.<br>".$e->getMessage();
}
catch (Exception $e) {
echo "General Error: The user could not be added.<br>".$e->getMessage();
}
}
?>
我的数据库表的结构是 studentID 作为主键自动递增,除了 dob 之外的所有字段都作为文本(dob 设置为日期时间)
发送数据的表单如下所示:
<form action="registersubmit.php" method="post">
First Name: <input type="text" autocomplete="off" name="fnameInput"><div id="erfirstname"></div><br>
Surname: <input type="text" autocomplete="off" name="snameInput"><div id="ersurname"></div><br>
Sex: <select id="sexInput" name="sexInput">
<option value="male">Male</option>
<option value="female">Female</option>
</select><div id="ersex"></div><br>
DOB: <input type="text" id="datepicker" name="dobInput"><div id="erdob"></p>
<input type="submit" name="pupilRegSubmit" value="Register" onclick="if(validatePupilReg()) this.form.submit()">
</form>
我没有收到 PDO 错误,但数据没有插入到表中。我认为这可能与日期选择器与 SQL 中的数据类型不匹配有关,但我不确定。有任何想法吗?
解决方案
在 PHP 中获取 MySQL 错误
您可以通过打印结果来了解 MySQLi 语句是否成功$statement->execute()
。引用 POD...
返回值
成功时返回 TRUE,失败时返回 FALSE。(来源:PHP.net)
如果它返回TRUE
,那么可能存在与语句失败不同的问题。
您还可以从 PHP 中的 MySQLi 包中使用error()
和来查看 MySQL 语句的结果。errno()
您没有在代码中列出它,但您必须$dbconn
以这样的方式定义......
$dbconn = new mysqli($hostname, $username, $password, $database);
执行 with 后$stmtUsr2 -> execute();
,尝试运行此代码...
print_r($dbconn->error);
print_r($dbconn->errno);
您的具体案例
更改日期选择器的格式以匹配 MySQL 的插入格式。
$(selector).datepicker({
dateFormat: 'yy-mm-dd',
});
更多帮助
我有另一个关于在这里获取更多调试信息的答案:debug_print_backtrace() to String for log-file。
推荐阅读
- google-maps-api-3 - 如何在 Google Maps JavaScript API 中启用 3D 卫星视图?
- javascript - 如何在particle.js中改变半径
- reactjs - 是否可以在 React 选择中使用 Array 作为选项
- python - 删除识别出的关键词之后的后续词
- angular - Angular Universal 中是否忽略了全局脚本?
- java - 如何删除 JScrollPane 上的 3D 边框
- glusterfs - 取消对磁盘的光泽?
- javascript - 重试失败的异步/承诺功能?
- swift - 如何在 WKWebView 完成加载之前运行函数?
- javascript - 单击时删除特定按钮(来自 DOM)