2016-04-11 29 views
2

我想使用PHP PDO準備語句插入值到MS SQL,我相信我已成功連接到SQL Server,但我不知道爲什麼我不能在它上面插入數據。PDO_SQLSRV返回沒有錯誤,不能插入值

這是我如何連接到SQL Server

<!DOCTYPE html> 
    <html> 
    <head> 
     <title></title> 
    </head> 
    <body> 
    <h1 align='center'>Paycom Projects</h1> 
    <h5 align='center'>Paycom CRUD</h5><br/> 
    <?php 
     $serverName = "EDGEWEBMEDIA-PC\SQLEXPRESS"; 

     /* Connect using Windows Authentication. */ 
     try 
     { 
      $conn = new PDO("sqlsrv:server=$serverName ; Database=paycom", "sa", "edgeweb"); 
      $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
     } 
     catch(Exception $e) 
     { 
      die(print_r($e->getMessage())); 
     } 

insert.php

<?php 

      include_once('connect.php'); 

      $stmt = $conn->prepare("INSERT INTO employee (firstname, lastname, email) 
       VALUES (:firstname, :lastname, :email)"); 
       $stmt->bindParam(':firstname', $firstname); 
       $stmt->bindParam(':lastname', $lastname); 
       $stmt->bindParam(':email', $email); 

       // insert a row 
       $firstname = "John"; 
       $lastname = "Doe"; 
       $email = "[email protected]"; 
       $stmt->execute() or die(print_r($stmt->errorInfo(), true)); 

       // insert another row 
       $firstname = "Mary"; 
       $lastname = "Moe"; 
       $email = "[email protected]"; 
       $stmt->execute() or die(print_r($stmt->errorInfo(), true)); 

       // insert another row 
       $firstname = "Julie"; 
       $lastname = "Dooley"; 
       $email = "[email protected]"; 
       $stmt->execute() or die(print_r($stmt->errorInfo(), true)); 

       echo "New records created successfully"; 
       } 
      catch(PDOException $e) 
       { 
       echo "Error: " . $e->getMessage(); 
       } 
      $conn = null; 

有什麼不對呢?我已經在同一臺機器上使用了Framework(Laravel),並且它完美地工作,但我想用普通的php(無框架)來測試它。

表,列手動通過SQL Management Studio中添加

UPDATE

現在我知道確切的錯誤是,當我加入

ini_set('display_errors',1); 
error_reporting(E_ALL | E_STRICT); 

現在的錯誤是空相關ID值

[Microsoft][SQL Server Native Client 11.0][SQL Server]Cannot insert the value NULL into column 'id', 

我更新的問題是,我有防止這個錯誤嗎?

更新

現在我能夠通過修改表中插入數據,id字段設置爲nullabler,但我知道這不能接受的,因爲我們執行的查詢

時,需要在表中的每個數據ID

回答

2

得到它

這是我如何解決它

刪除該表並重新創建

set id as not null, primary, and auto increment 

然後在設計

Under Indentity Specification, set (Is Identity)=Yes and Indentity Increment=1 

就是這樣