简体   繁体   English

SQLSTATE[HY093]:参数号无效:参数未定义

[英]SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

// 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);

This error you are receiving:您收到的此错误:

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined SQLSTATE[HY093]:参数号无效:参数未定义

is because the number of elements in $values & $matches is not the same or $matches contains more than 1 element.是因为$values & $matches中的元素数量不同或$matches包含超过 1 个元素。

If $matches contains more than 1 element, then the insert will fail, because there is only 1 column name referenced in the query( hash )如果$matches包含超过 1 个元素,则插入将失败,因为查询中仅引用了 1 个列名( 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 .如果$values & $matches不包含相同数量的元素,则插入也会失败,因为查询需要 x 参数但它正在接收 y 数据$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.代码在我的 XAMPP 服务器上运行,该服务器使用 PHP 5.3.8 和 MySQL 5.5.16。

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined SQLSTATE[HY093]:参数号无效:参数未定义

Unfortunately this error is not descriptive for a range of different problems related to the same issue - a binding error.不幸的是,此错误不能描述与同一问题相关的一系列不同问题 - 绑定错误。 It also does not specify where the error is, and so your problem is not necessarily in the execution, but the sql statement that was already 'prepared'.它也没有指定错误在哪里,因此您的问题不一定在执行中,而是已经“准备好”的 sql 语句。

These are the possible errors and their solutions:这些是可能的错误及其解决方案:

  1. There is a parameter mismatch - the number of fields does not match the parameters that have been bound.存在参数不匹配 - 字段数与已绑定的参数不匹配。 Watch out for arrays in arrays.注意数组中的数组。 To double check - use var_dump($var) .仔细检查 - 使用var_dump($var) " print_r " doesn't necessarily show you if the index in an array is another array (if the array has one value in it), whereas var_dump will. print_r ”不一定会显示数组中的索引是否是另一个数组(如果数组中有一个值),而var_dump会。

  2. You have tried to bind using the same binding value, for example: ":hash" and ":hash".您尝试使用相同的绑定值进行绑定,例如:“:hash”和“:hash”。 Every index has to be unique, even if logically it makes sense to use the same for two different parts, even if it's the same value.每个索引都必须是唯一的,即使在逻辑上对两个不同的部分使用相同的索引是有意义的,即使它是相同的值。 (it's similar to a constant but more like a placeholder) (它类似于一个常量,但更像一个占位符)

  3. If you're binding more than one value in a statement (as is often the case with an "INSERT"), you need to bindParam and then bindValue to the parameters.如果您在一个语句中绑定了多个值(通常是使用“INSERT”的情况),您需要先绑定参数,然后再绑定值到参数。 The process here is to bind the parameters to the fields, and then bind the values to the parameters.这里的过程是将参数绑定到字段,然后将值绑定到参数。

     // Code snippet $column_names = array(); $stmt->bindParam(':'.$i, $column_names[$i], $param_type); $stmt->bindValue(':'.$i, $values[$i], $param_type); $i++; //.....
  4. When binding values to column_names or table_names you can use `` but its not necessary, but make sure to be consistent.将值绑定到 column_names 或 table_names 时,您可以使用 `` 但它不是必需的,但请确保保持一致。

  5. Any value in '' single quotes is always treated as a string and will not be read as a column/table name or placeholder to bind to. '' 单引号中的任何值始终被视为字符串,不会被读取为要绑定的列/表名称或占位符。

I had the same error after using the wrong parameter name when binding.绑定时使用错误的参数名称后,我遇到了同样的错误。

Notice :tokenHash in the VALUES clause of the query, but :token_hash when binding.注意:tokenHash在查询的VALUES子句中,但:token_hash在绑定时。

Fixing one or the other resolved the error.修复一个或另一个解决了错误。

// Prepare DB connection
$sql = 'INSERT INTO rememberedlogins (token_hash,user_id,expires_at)
        VALUES (:tokenHash,:user_id,:expires_at)';
$db = static::getDB();
$stmt = $db->prepare($sql);

// Bind values
$stmt->bindValue(':token_hash',$hashed_token,PDO::PARAM_STR);

The same error I found will show if you have a mismatch of the column name in PHP & the database column name, Double check that too.如果您在 PHP 中的列名与数据库列名不匹配,我发现的相同错误将显示,请仔细检查。 This is what I had wrong.这就是我错了。

I understand that the answer was useful however for some reason it does not work for me however I have moved the situation with the following code and it is perfect我知道答案很有用但是由于某种原因它对我不起作用但是我已经使用以下代码改变了情况并且它是完美的

    <?php

$codigoarticulo = $_POST['codigoarticulo'];
$nombrearticulo = $_POST['nombrearticulo'];
$seccion        = $_POST['seccion'];
$precio         = $_POST['precio'];
$fecha          = $_POST['fecha'];
$importado      = $_POST['importado'];
$paisdeorigen   = $_POST['paisdeorigen'];
try {

  $server = 'mysql: host=localhost; dbname=usuarios';
  $user   = 'root';
  $pass   = '';
  $base   = new PDO($server, $user, $pass);

  $base->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  $base->query("SET character_set_results = 'utf8',
                     character_set_client = 'utf8',
                     character_set_connection = 'utf8',
                     character_set_database = 'utf8',
                     character_set_server = 'utf8'");

  $base->exec("SET character_set_results = 'utf8',
                     character_set_client = 'utf8',
                     character_set_connection = 'utf8',
                     character_set_database = 'utf8',
                     character_set_server = 'utf8'");

  $sql = "
  INSERT INTO productos
  (CÓDIGOARTÍCULO, NOMBREARTÍCULO, SECCIÓN, PRECIO, FECHA, IMPORTADO, PAÍSDEORIGEN)
  VALUES
  (:c_art, :n_art, :sec, :pre, :fecha_art, :import, :p_orig)";
// SE ejecuta la consulta ben prepare
  $result = $base->prepare($sql);
//  se pasan por parametros aqui
  $result->bindParam(':c_art', $codigoarticulo);
  $result->bindParam(':n_art', $nombrearticulo);
  $result->bindParam(':sec', $seccion);
  $result->bindParam(':pre', $precio);
  $result->bindParam(':fecha_art', $fecha);
  $result->bindParam(':import', $importado);
  $result->bindParam(':p_orig', $paisdeorigen);
  $result->execute();
  echo 'Articulo agregado';
} catch (Exception $e) {

  echo 'Error';
  echo $e->getMessage();
} finally {

}

?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM