code

PHP PDO 예외: "SQLSTATE[HY093]:잘못된 매개 변수 번호"

starcafe 2023. 9. 25. 22:53
반응형

PHP PDO 예외: "SQLSTATE[HY093]:잘못된 매개 변수 번호"

"SQLSTATE[HY093]" 오류가 발생합니다.아래 기능을 실행하려고 하면 잘못된 매개 변수 번호"가 나타납니다.

function add_persist($db, $user_id) {
    $hash = md5("per11".$user_id."sist11".time());
    $future = time()+(60*60*24*14);
    $sql = "INSERT INTO persist (user_id, hash, expire) VALUES (:user_id, :hash, :expire) ON DUPLICATE KEY UPDATE hash=:hash";
    $stm = $db->prepare($sql);
    $stm->execute(array(":user_id" => $user_id, ":hash" => $hash, ":expire" => $future));
    return $hash;
}

그냥 내가 못 잡는 단순한 것 같은 느낌이 듭니다.무슨 생각 있어요?

시도:

$sql = "INSERT INTO persist (user_id, hash, expire)
        VALUES (:user_id, :hash, :expire)
        ON DUPLICATE KEY UPDATE hash=:hash2";

그리고.

$stm->execute(
    array(":user_id" => $user_id, 
          ":hash" => $hash, 
          ":expire" => $future,
          ":hash2" => $hash)
);

문서에서 발췌(http://php.net/manual/en/pdo.prepare.php) :

PDOStatement::execute()를 호출할 때 문에 전달할 각 값에 대해 고유한 매개 변수 마커를 포함해야 합니다.준비된 문에는 동일한 이름의 명명된 파라미터 마커를 두 번 사용할 수 없습니다.SQL 문의 IN() 절과 같이 이름이 지정된 단일 매개 변수에는 여러 값을 바인딩할 수 없습니다.

이는 PDO를 사용하기 위한 한 가지 제한 사항입니다. PDO는 단순히 쿼리와 실행에 있는 매개 변수의 수를 인정하고 불일치할 경우 오류를 발생시킵니다.쿼리에서 매개 변수 반복을 사용해야 하는 경우 해결 방법을 사용하여 수행해야 합니다.

$sql = "insert into persist(user_id, hash, expire) values
    (:user_id, :hash, :value) on duplicate key update
    hash = :hash2";
$stm->execute(array(':user_id' => $user_id, ':hash' => $hash, ':hash2' => $hash,
    ':expire' => $expire));

좀 더 정교한 해결책을 위해 이것을 참조할 수 있습니다 - https://stackoverflow.com/a/7604080/1957346

이것이 오래된 질문이라는 것을 알고 있지만, SQL을 적절히 활용하여 PHP의 투박한 해결책을 피하는 것이 더 적절한 해결책이라는 것에 주목할 필요가 있다고 생각합니다.

INSERT INTO `persist` (`user_id`, `hash`, `expire`)
VALUES (:user_id, :hash, :expire)
ON DUPLICATE KEY UPDATE `hash`=VALUES(`hash`)

이렇게 하면 값을 한 번만 보내면 됩니다.

$stmt = $con->prepare("INSERT INTO items(Name, Description, Price, Country_Made, Status, Add_Date)  VALUES( :zname, :zdesc, :zprice, :zcountry, zstatus, now())");

$stmt-> execute(array(
   "zname" => $name,
   "zdesc" => $desc,
   "zprice" => $price,
   "zcountry" => $country,
   "zstatus" => $status 
));

언급URL : https://stackoverflow.com/questions/18028706/php-pdoexception-sqlstatehy093-invalid-parameter-number

반응형