我想使用PHP PDO准备的语句将值插入到MS SQL中,我确信我已经成功连接到SQL Server,但我不知道为什么不能在上面插入数据。
这就是我连接SQL服务器的方式
<!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 = "john@example.com";
$stmt->execute() or die(print_r($stmt->errorInfo(), true));
// insert another row
$firstname = "Mary";
$lastname = "Moe";
$email = "mary@example.com";
$stmt->execute() or die(print_r($stmt->errorInfo(), true));
// insert another row
$firstname = "Julie";
$lastname = "Dooley";
$email = "julie@example.com";
$stmt->execute() or die(print_r($stmt->errorInfo(), true));
echo "New records created successfully";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
这是怎么回事?我已经在同一台机器上使用框架(Laravel)尝试过了,它工作得很完美,但我想使用纯php(没有框架)来测试它。
表、列是通过sql management studio 手动添加的
更新
现在我知道确切的错误是,当我添加时
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
得到
就是这样解决的
放下表格并重新创建
set id as not null, primary, and auto increment
然后在设计
Under Indentity Specification, set (Is Identity)=Yes and Indentity Increment=1
就是