如何知道PDO是否在带有复合键的表中插入记录?
Yes, there are similar questions (i.e. 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.
Given the below query, $stmt->execute(array($doc_id,$id,$sites_id))
returns true
, however, a record is not inserted.
How do I determine whether PDO inserted a record?
EDIT. Please don't just say to use PDO::lastInsertId
, but if doing so is necessary, give a reason why it is necessary.
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 mysql:如何知道插入是否成功和 $ stmt-> execute():如何知道db insert是否成功?),但是, 提供的答案似乎对我不起作用。 p>
鉴于以下查询, 如何确定PDO是否插入了记录? p>
EDIT。 请不要只说使用 $ stmt-> execute(array($ doc_id,$ id,$ sites_id))返回
true code>,但是,未插入记录。 p>
PDO :: lastInsertId code>,但如果这样做是必要的,请说明必要的原因。 p>
INSERT INTO docx_priv_projects(documents_id,projects_id)
SELECT 2972614382,t.id
FROM项目AS t INNER JOIN实体AS e ON e.id = t.id
WHERE t.id = 1379519490 AND e.record_status ='active'AND e。 sites_id = 2416619273;
code> pre>
div>
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. Furthermore, it does not appear to work with composite keys.
pdo::rowCount()
is required. See http://php.net/manual/en/pdostatement.rowcount.php. Thanks given to AbraCadaver and 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:
Using the PDO API:
$stmt = $db->prepare("...");
$stmt->execute();
$id = $db->lastInsertId();
Using SQL instead of the 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.
http://php.net/manual/en/pdo.lastinsertid.php