1. 程式人生 > >php 原生pdo 接收get引數中文要打引號

php 原生pdo 接收get引數中文要打引號

e.g.

http://www.site1.com/?rout=getArticleByPeriodicalLevel&periodicalLevel='省級'

 

<?php
header("Content-type:text/html;charset=utf8");

ini_set("display_errors","On");
error_reporting(E_ALL);

//header('Content-type: application/json'); //json
$localhost = 'xxx.xxx.com';
$db_name = 'dbname';
$user_name = 'username';
$pass_word = 'password';


$db = new PDO("mysql:host={$localhost};dbname={$db_name}", $user_name, $pass_word,array(PDO::MYSQL_ATTR_INIT_COMMAND=>"set names utf8"));

function queryAll($db,$sql){
    $sth = $db->query($sql);
    return $sth->fetchAll(PDO::FETCH_ASSOC);

}

function getArticleAll($db)
{
    $sql = "SELECT * FROM article ";
    return queryAll($db,$sql);
}

function getArticlePagination($db,$index,$pageSize,$searchKey)
{
    $sql = "SELECT * FROM article limit {$index},{$pageSize} ";

    if(!empty($searchKey)){
        $sql = "SELECT * FROM article WHERE periodicalName CONCAT('%',{$searchKey}, '%') 
limit {$index},{$pageSize} ";
    }

    return queryAll($db,$sql);
}

function getArticle($db,$articleId)
{
    $sql = "SELECT * FROM article WHERE articleId = {$articleId}";
    return queryAll($db,$sql);

    //$sql = "SELECT * FROM article WHERE articleId = :articleId";
    //$stmt = $db->prepare($sql);
    //$stmt->execute(array(':articleId'=>$articleId));
    //return $stmt->fetchAll(PDO::FETCH_ASSOC);

}

function getArticleByPeriodicalLevel($db,$periodicalLevel)
{
    $sql = "SELECT * FROM article WHERE periodicalLevel = {$periodicalLevel}";
    return queryAll($db,$sql);
}


//路由入口
if(!empty($_GET['rout'])){

    // id查詢  /?rout=getArticle&articleId=1
    if($_GET['rout']=='getArticle')
    {
        $articleId = $_GET['articleId'];
        $ret = getArticle($db,$articleId);
        echo json_encode($ret);
    }

    // 查詢全部  /?rout=getArticleAll
    if($_GET['rout']=='getArticleAll')
    {
        $ret = getArticleAll($db);
        echo json_encode($ret);
    }

    // 分類查詢  /?rout=getArticleByPeriodicalLevel&periodicalLevel=5
    if($_GET['rout']=='getArticleByPeriodicalLevel')
    {
        $periodicalLevel = $_GET['periodicalLevel'];
        //var_dump(gettype($periodicalLevel));die;
        //$periodicalLevel = iconv("gb2312","utf-8",$periodicalLevel);
        $ret = getArticleByPeriodicalLevel($db,$periodicalLevel);
        echo json_encode($ret);
    }

    // 分頁查詢  /?rout=getArticlePagination&pageIndex=1&pageSize=2&searchKey
    if($_GET['rout']=='getArticlePagination')
    {
        $pageIndex = $_GET['pageIndex'];
        $pageSize = $_GET['pageSize'];
        $searchKey = $_GET['searchKey'];

        $skip = ((int)$pageIndex - 1) * (int)$pageSize ;
        $ret = getArticlePagination($db,$skip,$pageSize,$searchKey);

        echo json_encode($ret);
    }

}