来自 <form> 的数据未到达 DB 中的指定列

问题描述 投票:0回答:1

我的这个项目在我的笔记本电脑上运行得很好,它使用

UserName
将 3 个参数发送到数据库,
Expense
UserID
PDO
。它显示并输入
UserID
Expense
,但不显示
UserName
,它不会被发送到数据库并显示
NULL

这是每个文件的代码: 网页:

<form action="insertExpenses.php" method="POST">
    <div class="row mb-3">
      <label for="inputName" class="col-sm-2 col-form-label">إسمك</label>
      <div class="col-sm-10">
        <input type="text" class="form-control" id="UserName" name="UserName">
      </div>
    </div>
    <div class="row mb-3">
      <label for="inputEmail3" class="col-sm-2 col-form-label">رقم الهوية</label>
      <div class="col-sm-10">
        <input type="number" class="form-control" id="UserID" name="UserID">
      </div>
    </div>
    <div class="row mb-3">
      <label for="ExpenseInput" class="col-sm-2 col-form-label">قيمة النفقة</label>
      <div class="col-sm-10">
        <input type="number" class="form-control" id="Expense" name="Expense">
      </div>
    </div>
    <fieldset class="row mb-3">
      <legend class="col-form-label col-sm-2 pt-0">الخيارات</legend>
      <div class="col-sm-10">
        <div class="form-check">
          <input class="form-check-input" type="radio" name="gridRadio" id="gridRadio" value="option1" checked>
          <label class="form-check-label" for="gridRadio">
            إضافة نفقة
          </label>
        </div>
        <div class="form-check">
          <input class="form-check-input" type="radio" name="gridRadio" id="gridRadio" value="option2">
          <label class="form-check-label" for="gridRadio">
            تعديل نفقة
          </label>
        </div class="form-check">
          <input class="form-check-input" type="radio" name="gridRadio" id="gridRadio" value="option3" >
          <label class="form-check-label" for="gridRadio">
            حذف نفقة
          </label>
        </div>
    </fieldset>
    
    <div class="text-center">
      <button type="submit" class="btn btn-primary">Submit</button>
      <button type="reset" class="btn btn-secondary">Reset</button>
    </div>
  </form><!-- End Horizontal Form -->

这是 PHP 文件:

连接.php:

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "T14DB"; /*important to have all param the same*/

try {
  $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
  // set the PDO error mode to exception
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 echo "Connected successfully<br>";
} catch(PDOException $e) {
  echo "Connection failed: " . $e->getMessage();
}

插入费用.php:

<?php
include "connection.php"; //connect to the database and return $conn
try {
    $temp = $_POST["gridRadio"];
    $userID = $_POST['UserID'];
    if ($temp == "option1") { // insert or add expense
        echo "<br>Entered insert block<br>";
        $query = "INSERT INTO t14db.userfinances (`UserName`, `Expense`, `UserID`) 
                  VALUES (:UserName, :Expense, :UserID)";
        $stmt = $conn->prepare($query);

        $stmt->bindParam(':UserName', $_POST["UserName"]);
        $stmt->bindParam(':Expense', $_POST["Expense"]);
        $stmt->bindParam(':UserID', $_POST["UserID"]);

        if ($stmt->execute()) {
            displayUserData($conn, $userID);
        } else {
            echo "Error executing the query.";
        }


    } elseif ($temp == "option2") {//edit or update expense
        displayUserData($conn, $userID);
        $query = "update t14db.userfinances set `UserName`=:Username, Expense=:Expense where UserID=:UserID";
        $stmt = $conn->Prepare($query);
        $stmt->bindParam(':`UserID`', $_POST["UserID"]);
        $stmt->bindParam(':`UserName`', $_POST["UserName"]);
        $stmt->bindParam(':`Expense`', $_POST["Expense"]);
        if ($stmt->execute()) {
            echo "Data Changed successfully, here it is: <br>";

            $userID = $_POST['UserID'];
            $query2 = "SELECT `ID`, `UserName`, `Expense` from userfincaces where `UserID` = 'UserID'";
            $stmt = $conn->prepare($query2);
            $stmt->execute();
            if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                echo "ID: " . $row['UserID'] . "<br>";
                echo "NAME: " . $row['`UserName`'] . "<br>";
                echo "Expense: " . $row['Expense'] . "<br>";
            } else
                echo "The ID is not found in the table";

        }
    } elseif ($temp == "option3") {//delete expense or record
        displayUserData($conn, $userID);
        $query = "DELETE FROM t14db.userfinances WHERE UserID=:UserID";//Now Delete
        $stmt = $conn->prepare($query);
        $stmt->bindParam(':UserID', $userID);
        if ($stmt->execute()) {
            echo "record Deleted Successfully";
        }
    }
} catch (Exception $ex) {
    echo $ex->getMessage();
}


function displayUserData($conn, $userID)
{
    echo "<br>Entered DisplayUserData<br>";
    $query = "SELECT `UserID`, `UserName`, `Expense` FROM userfinances WHERE `UserID` = :UserID";
    $stmt = $conn->prepare($query);
    $stmt->bindParam(':UserID', $userID, PDO::PARAM_STR);
    $stmt->execute();

    if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        echo "--------------------------------------------<br>";
        echo "ID: " . $row['UserID'] . "<br>";
        echo "NAME: " . $row['UserName'] . "<br>";
        echo "Expense: " . $row['Expense'] . "<br>";
        echo "--------------------------------------------";
    } else {
        echo "--------------------------------------------";
        echo "The ID is not found in the table";
        echo "--------------------------------------------";
    }
}
$conn = null;

数据库导出文件为:

-- phpMyAdmin SQL Dump
-- version 5.2.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Mar 11, 2024 at 12:00 PM
-- Server version: 10.4.32-MariaDB
-- PHP Version: 8.2.12

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `t14db`
--

-- --------------------------------------------------------

--
-- Table structure for table `userfinances`
--

CREATE TABLE `userfinances` (
  `UserName` varchar(50) DEFAULT NULL,
  `Expense` int(11) NOT NULL,
  `UserID` int(11) NOT NULL,
  `Income` int(11) NOT NULL,
  `Debt` int(11) NOT NULL,
  `Qs` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

--
--
-- Indexes for table `userfinances`
--
ALTER TABLE `userfinances`
  ADD PRIMARY KEY (`UserID`);
COMMIT;

我的笔记本电脑中的输出如下:

Connected successfully

Entered insert block

Entered DisplayUserData
--------------------------------------------
ID: 3
NAME:
Expense: 950
--------------------------------------------

问题是:

  1. NAME
    未到达 DB,因此未通过显示功能显示
  2. 我的朋友根本没有向他的数据库发送任何数据

检查了参数名称,确保 php 文件和数据库中的列名称相同,测试了 copilot 建议的几乎所有可能的问题,但没有取得任何进展。

如何调试?

php sql forms pdo
1个回答
0
投票

这个问题是一个错字,一个要发布的新教训,永远不要在每次提交之前没有测试的情况下一次推送 20 个提交。我在该项目上所做的大部分工作都是在该分支进行的,并且没有测试大部分工作。结果是 13 次提交修复了拼写错误,并且还花了几个小时来完成我发现的其余 2 个拼写错误。

错别字1):

        if ($stmt->execute()) {
        displayUserData($conn, $userID);
    } else {
        echo "Error executing the query.";
    }

它是 HTML 文件中的 UserID,而不是 userID:

<input type="number" class="form-control" id="UserID" name="UserID">

正确的 php 代码:

        if ($stmt->execute()) {
    displayUserData($conn, $UserID);
} else {
    echo "Error executing the query.";
}

错字2):

        $userID = $_POST['UserID'];
        $query2 = "SELECT `ID`, `UserName`, `Expense` from userfincaces where `UserID` = 'UserID'";
        $stmt = $conn->prepare($query2);
        $stmt->execute();
        if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            echo "ID: " . $row['UserID'] . "<br>";
            echo "NAME: " . $row['`UserName`'] . "<br>";
            echo "Expense: " . $row['Expense'] . "<br>";
        } else
            echo "The ID is not found in the table";

    }

查询的列名不正确,ID->UserID。

错别字3:

    $stmt->bindParam(':`UserID`', $_POST["UserID"]);
    $stmt->bindParam(':`UserName`', $_POST["UserName"]);
    $stmt->bindParam(':`Expense`', $_POST["Expense"]);

只要是 : ,它就是一个 HTML 占位符,所以正确的代码是:

    $stmt = $conn->Prepare($query);
    $stmt->bindParam(':UserID', $_POST["UserID"]);
    $stmt->bindParam(':UserName', $_POST["UserName"]);
    $stmt->bindParam(':Expense', $_POST["Expense"]);

总共 1.2 小时+13 次提交,修复了 20 次提交在部署到存储库之前未测试的拼写错误。耐心和准确性的伟大教训。

回复评论:

  1. 来自@nbk,我应该从我的查询 bc 中得到一个错误,即不向其余的 clumns 提供值不正确,如果 NULL 可以的话,它将是 0 或保留 NULL。

  2. @droopsnot 更多地关注数据库设计概念,而不是代码问题。根据教授的要求,该表格应有 3 个输入并满足 3 个功能要求。因此,寻求项目的25点,而不是与他争论DB或Table设计概念。

  3. @droopsnot 用户名从未来自 HTML 表单,因为它没有前面提到的正确占位符拼写。

  4. @aynber 正确,后缀是数据库列而不是 HTML id 或名称

  5. 再次@aynber,纠正那里有一个拼写错误,修复它有助于解决问题

  6. @aynber,问题在于查询和占位符拼写不是“或”或'。特别是他引用的代码行也是用于回显数据,并且我在 phpmyadmin 中打开了数据库,但未在中显示数据UserName 列,因此 echo 不是问题,而是插入代码行。

希望这对社区其他人有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.