You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PostgreSQL数据表无法通过PHP代码更新问题求助

奖学金申请系统数据写入问题排查

我用PostgreSQL、PHP和HTML表单开发简易奖学金申请系统,数据库连接正常,提交表单后显示“Connected”无报错,但数据无法写入PostgreSQL表,求技术指导。

连接脚本(connect.php)

try {
    $dbConn = new PDO('pgsql:host=' . DB_HOST . ';'
                        . 'port=' . DB_PORT . ';'
                        . 'dbname=' . DB_NAME . ';'
                        . 'user=' . DB_USER . ';'
                        . 'password=' . DB_PASS);
    $dbConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // 设置错误模式为异常
    echo "Connected";
} catch (PDOException $e) {
    $fileName = basename($e->getFile(), ".php"); // 触发异常的文件
    $lineNumber = $e->getLine();          // 触发异常的行号
    die("[$fileName][$lineNumber] 数据库连接失败: " . $e->getMessage() . '<br/>');
}
?>

提交脚本(form.php)

<?php
require 'connect.php';

$sid = $_POST['sid'];
$firstName = $_POST['fname'];
$preferredName = $_POST['pname'];
$lastName = $_POST['lname'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$inSchool = $_POST['inSchool'];
$gDate = $_POST['gDate'];
$gpa = $_POST['gpa'];
$essay = $_POST['essay'];
$submit = $_POST['submit'];


if ($sid = ''){
    $query = 'insert into student(firstname,lastname,prefname,address,city,state,zip,phone,email) values (?,?,?,?,?,?,?,?,?)';
    $statement = $dbConn->prepare($query);
    $statement->execute([$firstname, $lastname,$preferredname,$address,$city,$state,$zip,$phone,$email]);
}
else{
    $query = 'insert into student(firstname,lastname,prefname,address,city,state,zip,phone,email) values (?,?,?,?,?,?,?,?,?)';
    $statement = $dbConn->prepare($query);
    $statement->execute([$firstname, $lastname,$preferredname,$address,$city,$state,$zip,$phone,$email]);
}
$query = 'select sid from student where firstname = ? and lastname = ? limit 1';
$statement = $dbConn->prepare($query);
$statement->execute([$firstname, $lastname,$preferredname,$address,$city,$state,$zip,$phone,$email]);
$results = $statement->fetch();

echo $results[0];

?>

HTML表单(Application.html)

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="Style.css">
    <title>Application</title>
</head>
    <body>
        <form action="form.php" method="post">
            <header>
                <img class="logo" src="" alt="logo">
                <div>Asterisks Corporation Scholarship Application</div>
            </header>

            <p class="general">Please fill in all information to apply for the Asterisk's Scholarship.<p>
            First Name:
                <input type="text" size="15" name="fname" required />
            Preferred Name:
                <input type="text" size="15" name="pname" >
            Last Name:
                <input type="text" size="15" name="lname" required />


            <p class="newSection">Contact Information</p>
            Address:
                <input type="text" size="50" name="address" required />
            City:
                <input type="text" size="15" name="city" required />
            State:
                <input type="text" size="15" name="state" required />
            Zip Code:
                <input type="text" size="1" name="zip" placeholder="####" required /><br><br>
            Phone Number:
                <input type="text" size="10" name="phone" placeholder="(###)-###-###">
            Email Address:
                <input type="text" size="50" name="email" required />


            <p class="newSection">Academic Information</p> 
            Are you currently enrolled in school?
                <input type="checkbox" id="Yes" name="yesBox">
                <label for="Yes">Yes</label>
                <input type="checkbox" id="No" name="noBox">
                <label for="No">No</label><br><br>
            What school are you enrolled?
                <input type="text" size="50" name="schoolsEnrolled"><br><br>
            What is/was your date of Graduation?
                <input type="date" name="graduationDate"><br><br>
            GPA
                <input type="text" size="1" name="gpa">


            <p class="newSection">What institutions have you applied?</p> 
            <input type="text" name="" value="" id="school" name="schoolsApplied">
            <button onclick="addToList()" type="button" name="button" id="addButton">Add School</button><br>
            <ul id="schoolList"></ul>

            <p class="newSection">Please write a small essay as to why you should receive this scholarship and what your plans are after graduation.</p>
            <textarea id="essay" style="width: 500px; height: 200px;" alignment="left" onkeyup="wordCounter(),wordsRemaining()" name="essay"></textarea>
            <div>
            300 Words Minimum & 500 Words Maximum 
            <div> Word Count: <span id="wordCount">0</span></div>
            <div> Words Remaining: <span id="wordsRemaining">0</span></div>
            
            </div>


            <p class="newSection">Please confirm each of the following:</p>
            <input type="checkbox" id="Transcript" name="transcriptConfirm" required />
                <label for="Transcript">I have sent in all of my transcripts</label><br>
            <input type="checkbox" id="Schools" name="schoolConfirm" required />
                <label for="Schools">All schools that I am considering are in the US</label><br>
            <input type="checkbox" id="Awards" name="awardConfirm" required />
                <label for="Awards">I understand that the award is $5,000 per year for four years</label><br>
            <input type="checkbox" id="Confirm" name="amountConfirm" required />
                <label for="Confirm">I have received confirmation that my recommenders have emailed their letters to the Scholarship's Coordinator</label><br><br>
            
            Please type your signature in the text box below: <br><br>
                <input type="text" size="20" name="signature" required />

            <div><br>    
            <input type="submit" value ="Submit" name="submit">
            <input type="reset" value="Start Over" onclick="MinMax()">
            </div>

            <script>
                function addToList(){
                let school= document.getElementById("school").value;
                document.getElementById("schoolList").innerHTML += ('<li>'+ school+'</li>');
                };

                function wordCounter(text){
                var count= document.getElementById("wordCount");
                var input= document.getElementById("essay");
                var text=essay.value.split(' ');
                var wordCount = text.length;
                count.innerText=wordCount
                }
                function wordsRemaining(text){
                var count= document.getElementById("wordCount");
                var input= document.getElementById("essay");
                var remaining = document.getElementById("wordsRemaining");
                var text=essay.value.split(' ');
                var wordCount = text.length;
                remaining.innerText=300-wordCount
                }


            </script>
        </form>
    </body>
</html>

问题排查与修复方案

1. 变量名大小写不一致

PHP是大小写敏感语言,代码中存在变量名大小写错误:

  • 定义的变量是$firstName、$preferredName,但执行SQL时用了$firstname、$preferredname,导致传递未定义的空值。
  • 修复:统一变量名大小写,将SQL执行中的变量改为$firstName、$preferredName。

2. 条件判断错误

if ($sid = '')是赋值语句而非判断语句,无论$sid原值是什么,都会被设为空字符串,导致永远走第一个分支。应改为相等判断:

if ($sid === ''){
    // 插入逻辑
}

另外,表单无sid字段,$sid = $_POST['sid'];会触发未定义索引警告,建议改用$sid = $_POST['sid'] ?? '';避免警告。

3. SELECT语句参数数量不匹配

SELECT语句仅定义2个占位符(firstname = ? and lastname = ?),但execute时传递了9个参数,会导致PDO抛出异常但可能未显示。修复为只传递对应数量的参数:

$statement->execute([$firstName, $lastName]);

4. 未处理潜在异常

虽然设置了ERRMODE_EXCEPTION,但提交脚本未用try-catch包裹数据库操作,异常出现时直接终止脚本且可能不显示详细错误。建议添加异常捕获:

try {
    // 所有数据库操作代码
} catch (PDOException $e) {
    die("数据库操作失败: " . $e->getMessage());
}

5. 表单字段与PHP接收不匹配

部分表单字段名和PHP接收变量不对应:

  • 毕业日期字段名是graduationDate,但PHP用$gDate = $_POST['gDate'];接收,导致未定义索引。
  • 在校状态用yesBox和noBox复选框,PHP用$inSchool = $_POST['inSchool'];无法获取正确值,建议改成单选按钮:
Are you currently enrolled in school?
<input type="radio" id="Yes" name="inSchool" value="yes" required>
<label for="Yes">Yes</label>
<input type="radio" id="No" name="inSchool" value="no" required>
<label for="No">No</label><br><br>

6. 未提交学校列表数据

动态添加的学校列表不会被提交到服务器,需将数据存储到隐藏字段:

<input type="hidden" name="schoolsAppliedList" id="schoolsAppliedList">

修改addToList函数:

function addToList(){
    let school= document.getElementById("school").value;
    let list = document.getElementById("schoolList");
    list.innerHTML += ('<li>'+ school+'</li>');
    let hiddenInput = document.getElementById("schoolsAppliedList");
    hiddenInput.value += (hiddenInput.value ? ',' : '') + school;
};

PHP中通过$schoolsApplied = $_POST['schoolsAppliedList'] ?? '';获取数据。

内容的提问来源于stack exchange,提问作者ILoveMusic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 12:21:12