Failed Execution of Multiple Insert Query: Cause and Solution
Executing a multi-part insert query can result in the following error message fail:
SQLSTATE[HY093]: Invalid parameter number: parameter was not defined
แม้ว่าก่อนเรียกใช้ count($matches) will match count($values), this error could occur.
The cause of this error is that the number of Elements in $values does not match the number of elements in $matches. If $values and $matches do not contain the same number of elements, the insert request fails because the query expects X parameters but only gets Y data elements ($matches). In this case, $values most likely already contains values. This is why the number of elements do not match.
To avoid this problem, an array must always be initialized before the loop.
In addition, it is necessary to ensure that the column "hash " contains a unique index.
Here is an example of a corrected code structure:
$matches = array('1'); $count = count($matches); $values = []; for($i = 0; $i < $count; ++$i) { $values[] = '(?)'; } // INSERT INTO DATABASE $sql = "INSERT INTO hashes (hash) VALUES " . implode(', ', $values) . " ON DUPLICATE KEY UPDATE hash=values(hash)"; $stmt = $dbh->prepare($sql); $data = $stmt->execute($matches);
The above is the detailed content of Why Does My Multi-Part INSERT Query Fail, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!