使用PDO自定义MySql查询

时间:2014-01-29 09:40:19

标签: php mysql sql pdo bind-variables

我正在使用关键字搜索($wordsToSearch)或某些类别标签字($tagsToSearch)来完全查询我的数据库。如果有的话。
这是我的功能,因为我使用concat添加查询的某些部分,所以它不安全。我应该如何使用PDO过滤变量,然后在必要时添加查询部分? 感谢大家

$wordsToSearch = " ";
$tagsToSearch = " ";

if(is_string($search)){
    $wordsToSearch = "WHERE (
                            `artist_nm` LIKE  '%".$search."%'
                            OR  `place` LIKE  '%".$search."%'
                            )";
}
if(is_string($searchtags)){
    $arrayTags = explode(',', $searchtags);
    $tagsToSearch = "HAVING (
                            `tags` LIKE  '%".$arrayTags[0]."%' ";
    foreach ($arrayTags as $key => $value) {
        if($key != 0 && $key <= 20)  {
            $tagsToSearch .= "OR `tags` LIKE  '%".$value."%' ";
        }
    }
    $tagsToSearch .= ")";

}

$database->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$STH = $database->prepare('SELECT id, lat, lng, CONCAT_WS(  "/&/", total, tags ) AS data
    FROM (SELECT lat, lng, id, CONCAT_WS(  "/&/", img_link, artist_nm, page_link, place, Total_Rating, Rating_Number ) AS total, GROUP_CONCAT( tag_name
    SEPARATOR  "," ) AS tags
    FROM images
    LEFT OUTER JOIN tbl_places ON images.id = tbl_places.KE_img
    LEFT OUTER JOIN rel_tags ON images.id = rel_tags.Id_immagine
    LEFT OUTER JOIN tags ON tags.Id_tag = rel_tags.Id_tag
    '.$wordsToSearch.'
    GROUP BY id '.$tagsToSearch.'
    ) AS subquery
    '); 
try {
    $STH->execute();
} catch(PDOException $e){
    echo $e->getMessage();
    die();
}

1 个答案:

答案 0 :(得分:0)

您正在寻找准备好的请求。您必须使用prepare()方法将参数编译为一些参数:

<?php

// With placeholders
$sth = $database->prepare('SELECT * FROM table WHERE id = ?'); 

// With named parameters
$sth = $database->prepare('SELECT * FROM table WHERE id = :id');

?>

然后您可以使用execute()方法执行查询:

<?php

// With placeholders
$sth->bindParam(1, $yourId, PDO::PARAM_INT);
$sth->execute();
// or
$sth->execute(array($yourId));

// With named parameters
$sth->bindParam(':id', $yourId, PDO::PARAM_INT);
$sth->execute();
// or
$sth->execute(array(':id' => $yourId));

?>

修改

当然你可以输入多个参数:

<?php

// With placeholders
$sth = $database->prepare('SELECT * FROM table WHERE username = ? AND password = ?');
$sth->bindParam(1, $username, PDO::PARAM_STR);
$sth->bindParam(2, $password, PDO::PARAM_STR);
$sth->execute();
// or
$sth->execute(array($username, $password));


// With named parameters
$sth = $database->prepare('SELECT * FROM table WHERE username = :username AND password = :password');
$sth->bindParam(':username', $username, PDO::PARAM_STR);
$sth->bindParam(':password', $password, PDO::PARAM_STR);
$sth->execute();
// or
$sth->execute(array(':username' => $username, ':password' => $password));

?>

the documentation中的更多信息。