无法使用 PDO SQLSRV 将数据插入 SQL 数据库

Cannot insert data into SQL db using PDO SQLSRV

我正在尝试学习为 sql 服务器数据库创建一个简单的 CRUD API。现在,我只能从数据库中获取 select table,现在我要将数据插入数据库。

但是我在使用 PDO SQLSRV 将值插入本地 SQL 服务器数据库时遇到问题。请指导我修复我的代码。

供您参考,我的 sql table 只使用 nvarchar, datetime, intnumeric 数据类型。

Table结构

AcCustomerID            | nvarchar(20)
AcCustomerName          | nvarchar(100)
AcTermID                | nvarchar(20)
AcAreaID                | nvarchar(20)
AcCusGroupID            | nvarchar(20)
AcCusUDGroupID          | nvarchar(20)
BillingAddress1         | nvarchar(100)
BillingAddress2         | nvarchar(100)
BillingAddress3         | nvarchar(100)
BillingAddress4         | nvarchar(100)
BillingTel1             | nvarchar(100)
BillingTel2             | nvarchar(100)
BillingFax1             | nvarchar(100)
BillingFax2             | nvarchar(100)
BillingPostalCode       | nvarchar(10)
BillingContact1         | nvarchar(100)
BillingContact2         | nvarchar(100)
BillingEmail            | nvarchar(100)
BillingHomePage         | nvarchar(100)
IsActive                | nvarchar(1)
Notes                   | nvarchar(MAX)
CreateBy                | nvarchar(20)
CreateDate              | datetime
EditBy                  | nvarchar(20)
EditDate                | datetime
Stamp                   | int
AcCustomerNickName      | nvarchar(100)
DateOfBirth             | datetime
IsMember                | nvarchar(1)
Gender                  | nvarchar(1)
MemberNo                | nvarchar(100)
MobileNo                | nvarchar(100)
IdentityNo              | nvarchar(100)
MemberJoinDate          | datetime
MemberExpireDate        | datetime
MemberMarriageDate      | datetime
AcMemberEthnicID        | nvarchar(20)
AcMemberIncomeID        | nvarchar(20)
AcMemberOccupationID    | nvarchar(20)
MemberPointBalance      | numeric(18, 2)
MemberPointAccumulated  | numeric(18, 4)
PriceCode               | nvarchar(1)
AcSalesmanID            | nvarchar(20)
IsGSTRegister           | nvarchar(1)
GSTRegisterNumber       | nvarchar(30)
BusinessRegisterNumber  | nvarchar(30)
AcCurrencyID            | nvarchar(5)
IsAllowPrintStatement   | nvarchar(1)
IsAllowExceedCreditTerm | nvarchar(1)
IsAllowExceedCreditLimit| nvarchar(1)
LocalCreditLimit        | numeric(18, 2)
LocalBalanceAmount      | numeric(18, 2)
AcTaxID                 | nvarchar(20)
IsAllowCreditSalesForPOS| nvarchar(1)
MemberNotes             | nvarchar(MAX)
AcINCardPackageID       | nvarchar(20)
AcCustomerIDParentID    | nvarchar(20)
TaxSLTRegistrationNo    | nvarchar(40)
TaxSVTRegistrationNo    | nvarchar(40)
AcTaxIDSST              | nvarchar(20)
SSTExemptionCertNumber  | nvarchar(30)

config/database.php

<?php
    class Database
    { 
        // specify your own database credentials
        private $host = "localhost\QNEBSS";
        private $db_name = "cafe99";
        private $username = "sa";
        private $password = "QnE123!@#";
        public $conn;

        // get the database connection
        public function getConnection()
        {

            $this->conn = null;

            try
            {
                $this->conn = new PDO("sqlsrv:Server=".$this->host.";Database=".$this->db_name, $this->username, $this->password);
                $this->conn->exec("set names utf8");
            }
            catch(PDOException $exception)
            {
                echo json_encode(array("message" => "Connection error: " . $exception->getMessage()));
            }

            return $this->conn;
        }
    }
?>

objects/customer.php

<?php
    class Customer
    { 
        // database connection and table name
        private $conn;
        private $table_name = "AcCustomer";

        // object properties
        public $AcCustomerID, $AcCustomerName, $AcTermID, $AcAreaID, $AcCusGroupID, $AcCusUDGroupID,
        $BillingAddress1, $BillingAddress2, $BillingAddress3, $BillingAddress4, $BillingTel1,
        $BillingTel2, $BillingFax1, $BillingFax2, $BillingPostalCode, $BillingContact1,
        $BillingContact2, $BillingEmail, $BillingHomePage, $IsActive, $Notes,
        $CreateBy, $CreateDate, $EditBy, $EditDate, $Stamp, $AcCustomerNickName,
        $DateOfBirth, $IsMember, $Gender, $MemberNo, $MobileNo, $IdentityNo,
        $MemberJoinDate, $MemberExpireDate, $MemberMarriageDate, $AcMemberEthnicID,
        $AcMemberIncomeID, $AcMemberOccupationID, $MemberPointBalance, $MemberPointAccumulated,
        $PriceCode, $AcSalesmanID, $IsGSTRegister, $GSTRegisterNumber, $BusinessRegisterNumber,
        $AcCurrencyID, $IsAllowPrintStatement, $IsAllowExceedCreditTerm, $IsAllowExceedCreditLimit,
        $LocalCreditLimit, $LocalBalanceAmount, $AcTaxID, $IsAllowCreditSalesForPOS,
        $MemberNotes, $AcINCardPackageID, $AcCustomerIDParentID, $TaxSLTRegistrationNo,
        $TaxSVTRegistrationNo, $AcTaxIDSST, $SSTExemptionCertNumber;


        // constructor with $db as database connection
        public function __construct($db)
        {
            $this->conn = $db;
        }

        // read customers
        function read()    
        {    
            // select all query
            $query = "SELECT * FROM ".$this->table_name." ORDER BY AcCustomerName ASC";

            // prepare query statement
            $stmt = $this->conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));

            // execute query
            $stmt->execute();

            return $stmt;
        }

        // create product
        function create()
        {
            // query to insert record
            $query = "INSERT INTO
                    " . $this->table_name . "
                    (
                        AcCustomerID, AcCustomerName, AcTermID,
                        AcAreaID, AcCusGroupID, AcCusUDGroupID,
                        BillingEmail, IsActive, CreateBy,
                        CreateDate, Stamp, DateOfBirth,
                        IsMember, Gender, MobileNo,
                        MemberJoinDate, MemberExpireDate, MemberMarriageDate,
                        AcMemberEthnicID, AcMemberIncomeID, AcMemberOccupationID,
                        MemberPointBalance, MemberPointAccumulated, PriceCode,
                        AcSalesmanID, IsGSTRegister, AcCurrencyID,
                        IsAllowPrintStatement, IsAllowExceedCreditTerm, IsAllowExceedCreditLimit,
                        LocalCreditLimit, LocalBalanceAmount, IsAllowCreditSalesForPOS,
                        AcCustomerIDParentID
                    )
                    VALUES
                    (
                        :AcCustomerID, :AcCustomerName, :AcTermID,
                        :AcAreaID, :AcCusGroupID, :AcCusUDGroupID,
                        :BillingEmail, :IsActive, :CreateBy,
                        :CreateDate, :Stamp, :DateOfBirth,
                        :IsMember, :Gender, :MobileNo,
                        :MemberJoinDate, :MemberExpireDate, :MemberMarriageDate,
                        :AcMemberEthnicID, :AcMemberIncomeID, :AcMemberOccupationID,
                        :MemberPointBalance, :MemberPointAccumulated, :PriceCode,
                        :AcSalesmanID, :IsGSTRegister, :AcCurrencyID,
                        :IsAllowPrintStatement, :IsAllowExceedCreditTerm, :IsAllowExceedCreditLimit,
                        :LocalCreditLimit, :LocalBalanceAmount, :IsAllowCreditSalesForPOS,
                        :AcCustomerIDParentID
                    )";

            // prepare query
            $stmt = $this->conn->prepare($query);

            // bind values
            $stmt->bindParam(":AcCustomerID", $this->AcCustomerID);
            $stmt->bindParam(":AcCustomerName", $this->AcCustomerName);
            $stmt->bindParam(":AcTermID", $this->AcTermID);
            $stmt->bindParam(":AcAreaID", $this->AcAreaID);
            $stmt->bindParam(":AcCusGroupID", $this->AcCusGroupID);
            $stmt->bindParam(":AcCusUDGroupID", $this->AcCusUDGroupID);
            $stmt->bindParam(":BillingEmail", $this->BillingEmail);
            $stmt->bindParam(":IsActive",$this->IsActive);
            $stmt->bindParam(":CreateBy",$this->CreateBy);
            $stmt->bindParam(":CreateDate",$this->CreateDate);
            $stmt->bindParam(":Stamp",$this->Stamp);
            $stmt->bindParam(":DateOfBirth",$this->DateOfBirth);
            $stmt->bindParam(":IsMember",$this->IsMember);
            $stmt->bindParam(":Gender",$this->Gender);
            $stmt->bindParam(":MobileNo",$this->MobileNo);
            $stmt->bindParam(":MemberJoinDate",$this->MemberJoinDate);
            $stmt->bindParam(":MemberExpireDate",$this->MemberExpireDate);
            $stmt->bindParam(":MemberMarriageDate",$this->MemberMarriageDate);
            $stmt->bindParam(":AcMemberEthnicID",$this->AcMemberEthnicID);
            $stmt->bindParam(":AcMemberIncomeID",$this->AcMemberIncomeID);
            $stmt->bindParam(":AcMemberOccupationID",$this->AcMemberOccupationID);
            $stmt->bindParam(":MemberPointBalance",$this->MemberPointBalance);
            $stmt->bindParam(":MemberPointAccumulated",$this->MemberPointAccumulated);
            $stmt->bindParam(":PriceCode",$this->PriceCode);
            $stmt->bindParam(":AcSalesmanID",$this->AcSalesmanID);
            $stmt->bindParam(":IsGSTRegister",$this->IsGSTRegister);
            $stmt->bindParam(":AcCurrencyID",$this->AcCurrencyID);
            $stmt->bindParam(":IsAllowPrintStatement",$this->IsAllowPrintStatement);
            $stmt->bindParam(":IsAllowExceedCreditTerm",$this->IsAllowExceedCreditTerm);
            $stmt->bindParam(":IsAllowExceedCreditLimit",$this->IsAllowExceedCreditLimit);
            $stmt->bindParam(":LocalCreditLimit",$this->LocalCreditLimit);
            $stmt->bindParam(":LocalBalanceAmount",$this->LocalBalanceAmount);
            $stmt->bindParam(":IsAllowCreditSalesForPOS",$this->IsAllowCreditSalesForPOS);
            $stmt->bindParam(":AcCustomerIDParentID",$this->AcCustomerIDParentID);

            // execute query
            if($stmt->execute())
            {
                return true;
            }

            return false;
        }
    }
?>

customer/create.php

<?php
    // required headers
    header("Access-Control-Allow-Origin: *");
    header("Content-Type: application/json; charset=UTF-8");
    header("Access-Control-Allow-Methods: POST");
    header("Access-Control-Max-Age: 3600");
    header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

    // get database connection
    include_once '../config/database.php';

    // instantiate product object
    include_once '../objects/customer.php';

    $database = new Database();
    $db = $database->getConnection();
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $customer = new Customer($db);

    // get posted data
    $data = json_decode(file_get_contents("php://input"));

    // make sure data is not empty
    if(!empty($data->AcCustomerID) 
        && !empty($data->AcCustomerName) 
        && !empty($data->BillingEmail) 
        && !empty($data->DateOfBirth) 
        && !empty($data->MobileNo)
    )
    {    
        // set product property values
        $customer->AcCustomerID = $data->AcCustomerID;
        $customer->AcCustomerName = $data->AcCustomerName; 
        $customer->AcTermID = "CASH";
        $customer->AcAreaID = "NA";
        $customer->AcCusGroupID = "NA";
        $customer->AcCusUDGroupID = "NA";
        $customer->BillingEmail = $data->BillingEmail;
        $customer->IsActive = "Y";
        $customer->CreateBy = "APP";
        $customer->CreateDate = date('Y-m-d H:i:s.u');
        $customer->Stamp = "0";
        $customer->DateOfBirth = date('Y-m-d H:i:s.u', strtotime($data->DateOfBirth));
        $customer->IsMember = "Y";
        $customer->Gender = "NA";
        $customer->MobileNo = $data->MobileNo;
        $customer->MemberJoinDate = date('Y-m-d H:i:s.u');
        $customer->MemberExpireDate = date('Y-m-d H:i:s.u', strtotime('+1 year'));
        $customer->MemberMarriageDate = date('Y-m-d H:i:s.u');
        $customer->AcMemberEthnicID = "NA" ;
        $customer->AcMemberIncomeID = "NA";
        $customer->AcMemberOccupationID = "NA";
        $customer->MemberPointBalance = "0.00";
        $customer->MemberPointAccumulated = "0.0000";
        $customer->PriceCode = "1";
        $customer->AcSalesmanID = "NA";
        $customer->IsGSTRegister = "N";
        $customer->AcCurrencyID = "MYR";
        $customer->IsAllowPrintStatement = "N";
        $customer->IsAllowExceedCreditTerm = "N";
        $customer->IsAllowExceedCreditLimit = "N";
        $customer->LocalCreditLimit = "0.00";
        $customer->LocalBalanceAmount = "0.00";
        $customer->IsAllowCreditSalesForPOS = "N";
        $customer->AcCustomerIDParentID = $data->AcCustomerID;            

        // create the product
        /*if($customer->create())
        {

            // set response code - 201 created
            http_response_code(201);

            // tell the user
            //echo json_encode(array("message" => "New Member was created."));
        }

        // if unable to create the product, tell the user
        else
        {

            // set response code - 503 service unavailable
            http_response_code(503);

            // tell the user
            echo json_encode(array("message" => "Unable to create new member."));
        }*/

        try 
        {
            if($customer->create())
            {

                // set response code - 201 created
                http_response_code(201);

                // tell the user
                echo json_encode(array("message" => "New Member was created."));
            }
        } 
        catch (PDOException $e) 
        {
            echo json_encode(array("message" => $e->getMessage()));
        }
    }

    // tell the user data is incomplete
    else
    {

        // set response code - 400 bad request
        http_response_code(400);

        // tell the user
        echo json_encode(array("message" => "Unable to create new member. Data is incomplete."));
    }
?>

输出

有 2 个问题

  1. 您的日期时间格式不正确,您将其设置为 date('Y-m-d H:i:s.u');,而应为 date('Y-m-d H:i:s');

  2. Gender 被设置为 'NA'(2 个字符),而 table 的 Gender 为 nvarchar(1),表示只有一个字符。将性别更改为一个字符或增加 nvarchar 限制。