PDO不会插入MYSQL DB参数号无效:参数未定义

时间:2013-04-04 14:38:27

标签: php mysql pdo

  

警告:PDOStatement :: execute()[pdostatement.execute]:   SQLSTATE [HY093]:参数号无效:参数未定义

<?php
$firstname = $_POST['first-name'];
$lastname = $_POST['last-name'];
$company = $_POST['company'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$country = $_POST['country'];
$type = $_POST['type'];
$source = "IP-Demo";

// query
$sql = "INSERT INTO Contact (first-name,last-name,Company,email,phone,city,state,zip,country,type,source)
    VALUES (:first-name,:last-name,:Company,:email,:phone,:city,:state,:zip,:country,:type,:source)";

$q = $conn->prepare($sql);
$q->execute(array(
    ':first-name'=>$firstname,
    ':last-name'=>$lastname,
    ':Company'=>$company,
    ':email'=>$email,
    ':phone'=>$phone,
    ':city'=>$city,
    ':state'=>$state,
    ':zip'=>$zip,
    ':country'=>$country,
    ':type'=>$type,
    ':source'=>$source
));

3 个答案:

答案 0 :(得分:1)

您的查询包含几个需要反引号引用的对象名称,至少包括:

  • first-name
  • last-name
  • type

修改:顺便说一句,只是尝试了您的代码而prepare()失败了:

  

PHP致命错误:带有消息的未捕获异常'PDOException'   'SQLSTATE [42000]:语法错误或访问冲突:1064您有   SQL语法错误;查看与您的手册相对应的手册   MySQL服务器版本为正确的语法使用附近   “-name,最后姓名,公司,电子邮件,电话,城市,州,邮编,国家,类型,源)

答案 1 :(得分:0)

您的陈述假设type为保留字而不是列名,因此它提供10列和11个参数

尝试在列名称的前面和末尾设置`char

答案 2 :(得分:0)

当使用real db abstraction库而不是那个不方便且有限的PDO时,所有代码都只有几行。更不用说它永远不会因为被遗忘的引用这样一个愚蠢的理由而失败。

$allowed = explode(',','first-name,last-name,Company,email,phone,city,state,zip,country,type');
$data = $db->filterArray($_POST,$allowed);
$db->query("INSERT INTO Contact SET ?u", $data);