[英]How to know if PDO inserted a record on a table with a composite key?
Yes, there are similar questions (ie PDO mysql: How to know if insert was successful and $stmt->execute() : How to know if db insert was successful? ), however, the supplied answers don't seem to work for me. 是的,也有类似的问题(即PDO mysql:如何知道插入是否成功,以及$ stmt-> execute():如何知道数据库插入是否成功? ),但是,提供的答案似乎不适用于我。
Given the below query, $stmt->execute(array($doc_id,$id,$sites_id))
returns true
, however, a record is not inserted. 给定以下查询, $stmt->execute(array($doc_id,$id,$sites_id))
返回true
,但是未插入记录。
How do I determine whether PDO inserted a record? 如何确定PDO是否插入了记录?
EDIT. 编辑。 Please don't just say to use PDO::lastInsertId
, but if doing so is necessary, give a reason why it is necessary. 请不要只是说要使用PDO::lastInsertId
,而是如果有必要这样做,请说明为什么有必要这样做。
INSERT INTO docx_priv_projects (documents_id,projects_id)
SELECT 2972614382,t.id
FROM projects AS t INNER JOIN entities AS e ON e.id=t.id
WHERE t.id=1379519490 AND e.record_status='active' AND e.sites_id=2416619273;
PDO::lastInsertId
appears to only work on auto incremented PKs, however, this requirement does not seem to be documented very well at http://php.net/manual/en/pdo.lastinsertid.php . PDO::lastInsertId
似乎仅适用于自动递增的PK,但是,在http://php.net/manual/zh/pdo.lastinsertid.php上似乎没有很好地记录此要求。 Furthermore, it does not appear to work with composite keys. 此外,它似乎不适用于复合键。
pdo::rowCount()
is required. pdo::rowCount()
是必需的。 See http://php.net/manual/en/pdostatement.rowcount.php . 参见http://php.net/manual/en/pdostatement.rowcount.php 。 Thanks given to AbraCadaver and Ryan Vincent. 感谢AbraCadaver和Ryan Vincent。
$sql='INSERT INTO docx_priv_projects (documents_id,projects_id)
SELECT :doc_id,t.id
FROM projects AS t INNER JOIN entities AS e ON e.id=t.id
WHERE t.id=:id AND e.record_status='active' AND e.sites_id=:sites_id';
$stmt = $conn->prepare($sql);
$stmt->execute(array('id'=>1379519490 ,'sites_id'=>2416619273,'doc_id'=>2972614382));
$x=$stmt->rowCount(); //Will be `1` if added
You can test if there was a last inserted id in two ways: 您可以通过两种方式测试是否最后插入了一个ID:
Using the PDO API: 使用PDO API:
$stmt = $db->prepare("...");
$stmt->execute();
$id = $db->lastInsertId();
Using SQL instead of the PDO API: 使用SQL代替PDO API:
$stmt = $db->query("SELECT LAST_INSERT_ID()");
$lastId = $stmt->fetch(PDO::FETCH_NUM);
$lastId = $lastId[0];
Then test for example is, lastid or id is int > 1 or do your own validation. 然后测试例如,lastid或id为int> 1或进行您自己的验证。
http://php.net/manual/en/pdo.lastinsertid.php
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.