Home >Database >Mysql Tutorial >Why Does My Multiple Insert Query Throw an 'Invalid Parameter Number' Error Despite Matching Parameter Counts?
Error Handling: "Invalid Parameter Number" in Multiple Insert Query
When attempting to perform a multiple insert query, it's crucial to ensure that the number of parameter values matches the number of placeholders in the query itself. However, the following code encounters the error "SQLSTATE[HY093]: Invalid parameter number: parameter was not defined," despite confirming that count($matches) and count($values) are equal just before the query is executed.
// BUILD VALUES $count = count($matches); for($i = 0; $i < $count; ++$i) { $values[] = '(?)'; } // INSERT INTO DATABASE $q = $this->dbc->prepare("INSERT INTO hashes (hash) VALUES " . implode(', ', $values) . " ON DUPLICATE KEY UPDATE hash = hash"); $q->execute($matches);
The discrepancy between the code and the error message stems from a potential issue in the initialization of the $values array. It's likely that $values already contains some data, leading to a count mismatch. To prevent this, it's essential to always initialize arrays before the loop.
To resolve the issue, consider the following modified code:
$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);
Additionally, to avoid the "Invalid parameter number" error in multiple insert queries, ensure that the column used for duplicate key updates (in this case, hash) has a unique index defined. Failure to do so may result in unexpected behavior and potential errors.
The above is the detailed content of Why Does My Multiple Insert Query Throw an 'Invalid Parameter Number' Error Despite Matching Parameter Counts?. For more information, please follow other related articles on the PHP Chinese website!