SQLSTATE[HY093]: Invalid parameter number: parameter was not defined(SQLSTATE[HY093]:参数号无效:参数未定义)
问题描述
// 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 code above fails with the following error
SQLSTATE[HY093]:参数号无效:参数未定义
虽然当 count($matches) == count($values)
在执行之前被调用?
Although when count($matches) == count($values)
just before execute is called?
这是怎么回事?
推荐答案
您收到此错误:
SQLSTATE[HY093]:参数号无效:参数未定义
是因为$values
中的元素个数&$matches
不相同或 $matches
包含超过 1 个元素.
is because the number of elements in $values
& $matches
is not the same or $matches
contains more than 1 element.
如果 $matches
包含超过 1 个元素,则插入将失败,因为查询中只引用了 1 个列名(hash
)
If $matches
contains more than 1 element, then the insert will fail, because there is only 1 column name referenced in the query(hash
)
如果 $values
&$matches
不包含相同数量的元素,那么插入也会失败,因为查询需要 x 参数但它正在接收 y 数据 $matches
.
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.
试试代码这里:
<?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());
?>
你需要稍微调整一下.
我使用的表结构是这里:
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 ;
代码在我的 XAMPP 服务器上运行,该服务器使用 PHP 5.3.8 和 MySQL 5.5.16.
Code was run on my XAMPP Server which is using PHP 5.3.8 with MySQL 5.5.16.
这篇关于SQLSTATE[HY093]:参数号无效:参数未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SQLSTATE[HY093]:参数号无效:参数未定义
基础教程推荐
- Libpuzzle 索引数百万张图片? 2022-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- 在多维数组中查找最大值 2021-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- 超薄框架REST服务两次获得输出 2022-01-01