This error you are receiving:
SQLSTATE[HY093]: Invalid parameter number: parameter was not defined
is because the number of elements in $values
& $matches
is not the same or $matches
contains more than 1 element.
If $matches
contains more than 1 element, then the insert will fail, because there is only 1 column name referenced in the query(hash
)
If $values
& $matches
do not contain the same number of elements then the insert will also fail, due to the query expecting x params but it is receiving y data $matches
.
I believe you will also need to ensure the column hash has a unique index on it as well.
Try the code here:
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'root';
/*** mysql password ***/
$password = '';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=test", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
$matches = array('1');
$count = count($matches);
for($i = 0; $i < $count; ++$i) {
$values[] = '?';
}
// INSERT INTO DATABASE
$sql = "INSERT INTO hashes (hash) VALUES (" . implode(', ', $values) . ") ON DUPLICATE KEY UPDATE hash='hash'";
$stmt = $dbh->prepare($sql);
$data = $stmt->execute($matches);
//Error reporting if something went wrong...
var_dump($dbh->errorInfo());
?>
You will need to adapt it a little.
Table structure I used is here:
CREATE TABLE IF NOT EXISTS `hashes` (
`hashid` int(11) NOT NULL AUTO_INCREMENT,
`hash` varchar(250) NOT NULL,
PRIMARY KEY (`hashid`),
UNIQUE KEY `hash1` (`hash`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Code was run on my XAMPP Server which is using PHP 5.3.8 with MySQL 5.5.16.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…