在PDO中使用SHOW COLUMNS和LIKE子句

时间:2014-09-05 03:54:02

标签: php mysql sql pdo sql-like

我不知道为什么这不起作用:

    $stmt_field_exists = $db->prepare("SHOW COLUMNS
        FROM uf_users
        LIKE :field_name");

    $sqlVars[':field_name'] = "%display_name%";

我在prepare声明中收到错误, SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 3

起初我以为我要么错误地使用SHOW COLUMNS查询,要么错误地形成占位符,但是当我单独尝试这两个中的任何一个时,它们都能正常工作:

    // Works fine
    $stmt_field_exists = $db->prepare("SELECT display_name
        FROM uf_users
        WHERE display_name LIKE :value");

    $sqlVars[':value'] = "%admin%";


    // Also works fine
    $stmt_field_exists = $db->prepare("SHOW COLUMNS
        FROM uf_users
        LIKE '%display_name%'");

我正在使用MySQL 5.5.31。到底发生了什么事?我找到了一个错误吗?

1 个答案:

答案 0 :(得分:0)

完整功能如下:

function fetchUserField($user_id, $field_name){    
try {
    global $db_table_prefix;

    $db = pdoConnect();

    $sqlVars = array();

    // First, check that the specified field exists.  Very important as we are using other unsanitized data in the following query.
    $stmt_field_exists = $db->prepare("SHOW COLUMNS
        FROM ".$db_table_prefix."users
        LIKE :field_name");

    $sqlVars[':field_name'] = "%" . $field_name . "%";

    $stmt_field_exists->execute($sqlVars);

    if (!($results = $stmt_field_exists->fetch(PDO::FETCH_ASSOC))){
        // The field does not exist
        return false;
    }

    $query = "SELECT 
        `$field_name`
        FROM ".$db_table_prefix."users
        WHERE
        id = :user_id
        LIMIT 1";

    $stmt = $db->prepare($query);

    $sqlVars[':user_id'] = $user_id;

    $stmt->execute($sqlVars);

    if (!($results = $stmt->fetch(PDO::FETCH_ASSOC))){
        // The user does not exist
        return false;
    }

    $stmt = null;
    return $results[$field_name];

} catch (PDOException $e) {
  addAlert("danger", "Oops, looks like our database encountered an error.");
  error_log("Error in " . $e->getFile() . " on line " . $e->getLine() . ": " . $e->getMessage());
  return false;
} catch (ErrorException $e) {
  addAlert("danger", "Oops, looks like our server might have goofed.  If you're an admin, please check the PHP error logs.");
  return false;
}

}

简单地使用它

// Return the timestamp when this user's account was registered 
$author = fetchUserField($user_id, $field);

这无法提取数据,但由于某种原因只是保持返回false。