Php PDO:无效参数编号:绑定变量的数量与令牌的数量不匹配…但计数确实匹配

Php PDO:无效参数编号:绑定变量的数量与令牌的数量不匹配…但计数确实匹配,php,pdo,Php,Pdo,我得到了一条清晰的错误信息: Invalid parameter number: number of bound variables does not match number of tokens 我以前得到过,这总是因为我忘记了冒号,或者因为绑定变量的数量与标记的数量不匹配(想象一下) 在今天的例子中,我无法理解为什么会出现这个错误。我有六个绑定变量,六个冒号和六个标记。绑定前的var_dumping为$this->productId和所有$this->contents[]值输出正确的值,因

我得到了一条清晰的错误信息:

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

有什么明显的地方值得您注意吗?

您需要在绑定到PDO语句之前使用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()

prepare
语句在哪里?可能是Nah的副本,而不是Nah的副本。我忘了准备陈述,所以答案很不一样:(
$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();