PDO:参数号无效:绑定变量数与令牌数不匹配...但计数DO匹配

时间:2014-07-23 16:57:38

标签: php pdo

我得到的应该是一个明确的错误信息:

Invalid parameter number: number of bound variables does not match number of tokens

我之前已经知道了,而且总是因为我忘记了冒号,或者因为绑定变量的数量与令牌的数量不匹配(想象一下)。

在今天的情况下,我无法弄清楚为什么我会收到此错误。我有六个绑定变量,六个冒号和六个令牌。绑定前的var_dumping输出$ this-> productId和所有$ this-> contents []值的正确值,所以一切都正确且非空进入绑定过程。

这是我正在使用的代码:

$sql = 'insert into courses 
        (product_id, title, price, length, body_about, body_outline, body_profile, body_prerequisites, status_id) 
        values 
        (:product_id, :title, "0", "0", :body_about, :body_outline, :body_profile, :body_prerequisites, "1")';

$s -> bindValue(':product_id', $this->productId);
$s -> bindValue(':title', $this->contents['title']);
$s -> bindValue(':body_about', $this->contents['overview']);
$s -> bindValue(':body_outline', $this->contents['outline']);
$s -> bindValue(':body_profile', $this->contents['audience']);
$s -> bindValue(':body_prerequisites', $this->contents['prerequisites']);               
$s -> execute();

你有什么明显的优势吗?

2 个答案:

答案 0 :(得分:2)

您需要在绑定之前使用prepare创建PDO语句$s

// 1. setup the connection
$db = new PDO($dsn, $user, $pass);

// 2. write your sql
$sql = 'insert into courses (product_id, title, price, length, body_about, body_outline, body_profile, body_prerequisites, status_id)  values (:product_id, :title, "0", "0", :body_about, :body_outline, :body_profile, :body_prerequisites, "1")';

// 3. generate the prepared statement object
$s = $db->prepare($sql);

// 4. NOW, you can bind values...
$s -> bindValue(':product_id', $this->productId);
$s -> bindValue(':title', $this->contents['title']);
$s -> bindValue(':body_about', $this->contents['overview']);
$s -> bindValue(':body_outline', $this->contents['outline']);
$s -> bindValue(':body_profile', $this->contents['audience']);
$s -> bindValue(':body_prerequisites', $this->contents['prerequisites']);    

// 5. Finally execute the statement!           
$s -> execute()

答案 1 :(得分:1)

$sql = 'insert into courses 
        (product_id, title, price, length, body_about, body_outline, body_profile, body_prerequisites, status_id) 
        values 
        (:product_id, :title, "0", "0", :body_about, :body_outline, :body_profile, :body_prerequisites, "1")';

$s = $db -> prepare($sql);               // NOTE THIS
$s -> bindValue(':product_id', $this->productId);
$s -> bindValue(':title', $this->contents['title']);
$s -> bindValue(':body_about', $this->contents['overview']);
$s -> bindValue(':body_outline', $this->contents['outline']);
$s -> bindValue(':body_profile', $this->contents['audience']);
$s -> bindValue(':body_prerequisites', $this->contents['prerequisites']);               
$s -> execute();