PDO逃脱&在查询中

时间:2012-11-23 02:23:12

标签: php mysql pdo

我正在使用PDO进行查询并试图逃避一些'&'因为他们使请求无效。我已经尝试过mysql_real_escape_string和pdo引用......两者都没有逃过'&'。我的价值观是“James& Jack”。

作为连接器:

$this->connect = new PDO("mysql:host=$db_host;dbname=$db_name;", $db_user, $db_pass,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));

作为查询:

function check_exist($query,$parameter)
{
    try
    {
    $this->connect->prepare($query);
    $this->connect->bindParam(':parameter', $parameter, PDO::PARAM_STR);
    $this->connect->execute();
    return $this->connect->fetchColumn();


        unset ($query);
    }
    catch(PDOException $e) 
    {  
        echo $e->getMessage(); 
    }

}

最终行动呼吁

$db = new database;
$db->connect('framework','localhost','root','');
$result = $db->check_exist('SELECT COUNT(*) FROM cat_merge WHERE cat=:parameter',$cat);

1 个答案:

答案 0 :(得分:3)

尝试以这种方式使用预准备语句:

<?php
// Connect to the database
$db = new PDO('mysql:host=127.0.0.1;dbname=DB_NAME_HERE', 'username', 'password');
// Don't emulate prepared statements, use the real ones
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
// Prepare the query
$query = $db->prepare('SELECT * FROM foo WHERE id = ?');
// Execute the query
$query->execute($_GET['id']);
// Get the result as an associative array
$result = $query->fetchAll(PDO::FETCH_ASSOC);
// Output the result
print_r($result);
?>