首页 > 解决方案 > 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 中的数据类型不匹配有关,但我不确定。有任何想法吗?

标签: phpsql

解决方案


在 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


推荐阅读