Home >Database >Mysql Tutorial >Why Does My Multiple Insert Query Return 'Invalid Parameter Number'?
When attempting to insert multiple records into a database table, you may encounter the "Invalid parameter number: parameter was not defined" error. This occurs when the number of parameters specified in the query does not match the number of values provided as input.
In the provided code snippet:
$matches = array('1'); $count = count($matches); for($i = 0; $i < $count; ++$i) { $values[] = '(?)'; } // Build query $q = $this->dbc->prepare("INSERT INTO hashes (hash) VALUES " . implode(', ', $values) . " ON DUPLICATE KEY UPDATE hash = hash"); $q->execute($matches);
The goal is to insert the value in $matches into the hashes table, using a prepared statement. However, the error occurs because the number of placeholder parameters (?) in the $values array does not correspond to the actual data in $matches.
To resolve this issue, ensure the following:
$matches = array('1'); $values = []; $count = count($matches); for($i = 0; $i < $count; ++$i) { $values[] = '(?)'; } // Insert query with named parameters (:hash) $sql = "INSERT INTO hashes (hash) VALUES (:hash) ON DUPLICATE KEY UPDATE hash = VALUES(:hash)"; $stmt = $dbh->prepare($sql); $data = $stmt->execute([':hash' => $matches]);
The above is the detailed content of Why Does My Multiple Insert Query Return 'Invalid Parameter Number'?. For more information, please follow other related articles on the PHP Chinese website!