错误:SQLSTATE [HY093]:无效的参数编号:绑定变量的数量与令牌的数量不匹配 [英] ERROR: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens

查看:1388
本文介绍了错误:SQLSTATE [HY093]:无效的参数编号:绑定变量的数量与令牌的数量不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看到这是一个错误的绑定错误(正在搜索stackoverflow),但是看来我绑定了所有变量,而且没有错别字....我在这里没有明显的地方吗?

saw this was an error with incorrect binding (searching stackoverflow), but it looks like I have all variables bound and no typos.... am I missing the obvious here?

function connect () {
global $pdo;
try {
    $pdo = new PDO("mysql:host=localhost;dbname=test", "root", "root");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
  }
}

function getPhotos ($status = 0, $type = null, $session = null, $name = null) {
global $pdo;
try {
    $sql = 'SELECT * FROM images WHERE 1=1';

    //Status Filter Query
    $sql .=' AND status = :status';

    //Type Filter Query
    if (!is_null($type)) {
        $sql .=' AND type = :type';
    }

    // Session Filter Query
    if (!is_null($session)) {
        $sql .=' AND session = :session';
    }

    // Twitter Handle Filter Query
    if (!is_null($name)) {
        $sql .=' AND handle = :name';
    }

    //Prepare The Query
    $stmt = $pdo->prepare($sql);

    //Fire The Lasers
    $stmt->execute(array(':status' => $status, ':type' => $type, ':session' => $session, ':name' => $name));

    //Grab 
    return $stmt->fetchAll();

推荐答案

仅在将变量实际添加到查询时绑定它们:

Only bind the variables when you actually add them to the query:

//Status Filter Query
$sql .=' AND status = :status';

$vars = array(':status' => $status);

//Type Filter Query
if (!is_null($type)) {
    $sql .=' AND type = :type';
    $vars[':type'] = $type;
}

// Session Filter Query
if (!is_null($session)) {
    $sql .=' AND session = :session';
    $vars[':session'] = $session;
}

// etc.

$stmt->execute($vars);

这篇关于错误:SQLSTATE [HY093]:无效的参数编号:绑定变量的数量与令牌的数量不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆