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::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