开发者

PHP: Inserting using sqlsrv pdo using triggers

I'm using sqlsrv pdo driver (used both 5.2 and 5.3 versions) and I'm seeing what I believe is unintended behavior. Hopefully I'm doing something wrong.

I've created 2 tables in sql express 2008. One (Locations) is a table of primary keys shared with other tables. The other table (Rooms) has 2 (or more) columns...a key column linked as a foreign key to the first table and one (or more) data columns. So it looks like:

Locations

LocationID int

1

2

3

4

5

Rooms

LocationID int, Roomname varchar(50)

2, 'living'

4, 'dining'

2,4 both link back to the Locations table.

Then I create a unique constraint on the Roomname column:

ALTER TABLE Rooms ADD CONSTRAINT UniqueRoom UNIQUE (Roomname)

Next, I created an INSTEAD OF INSERT trigger on the Rooms table:

CREATE TRIGGER [dbo].[Rooms_INSERT] 
on [dbo].Rooms 
INSTEAD OF INSERT 
as 
BEGIN 
 INSERT INTO dbo.Locations DEFAULT VALUES 
 INSERT INTO dbo.Rooms select @@IDENTITY, Roomname from inserted    
END  

Now I can insert data into the rooms table by:

开发者_开发知识库INSERT INTO Rooms VALUES (null, 'roomname')

I use the sqlsrv PDO object to insert data through PHP:

$db = new PDO("sqlsrv:server=$serverName;Database=db", "", "");

$sql=("insert into Rooms values (null,?)");
$dbobj = $db->prepare($sql);
if($dbobj->execute(array("dining")))
    print "<p>insert successful</p>";
else
    print "<p>insert unsuccessful</p>";

Starting with the table listing above, I get the following results:

  • Modify insert statement to "insert into Rooms values (?)" - fails as expected because it expects two args, "insert unsuccessful."
  • Revert insert statement to normal, attempt to insert array("bedroom") - successful as expected, "insert successful."
  • Re-attempt insert of array("bedroom") - db insert fails, no entries are made in either table, but attempt is reported successful "insert successful."

Why is the 3rd attempt reported as successful when there were no lasting entries made to the database? Or, more specifically, how can I modify either my PHP or my SQL to properly detect when an insert like this fails due to a violation of a unique constraint?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜