duanchun2349 2015-10-14 09:02
浏览 64
已采纳

php PDO bindParam()width 2维数组 - foreach循环

can I ask somebody is this good solution (value is passed to bindParam() in foreach as follows: $var_value = &$row['val'];) or is it better solution for it ?

I have array for example:

$array['city']['val']        = $city;  //city value passed to bindParam()
$array['city']['type']       = 'string'; //type passed to bindParam()
$array['city_id']['val']     = $city_id;   
$array['city_id']['type']    = 'int';     

$query = "update cities set city=:city where city_id=:city_id"; 

function to bind parameters:

function BindParameters($array,$query) {

        $st = $this->dbc->prepare($query);   

        if (is_array($array) && count($array)>0) {

            foreach ($array as $key=> $row) {

                if (isset($row['type'])) {
                    $var_type  = $row['type'];
                } else {
                    $var_type  = '';
                }

                $var_value =  &$row['val']; 

                if ($var_type=='int') {
                    $var_type = PDO::PARAM_INT;
                } else if ($var_type=='string') {
                    $var_type = PDO::PARAM_STR;
                } else if ($var_type=='null') {
                    $var_type = PDO::PARAM_NULL;
                } else {
                    $var_type = PDO::PARAM_STR;
                }
                $st->bindParam(':'.$key,$var_value,$var_type);
            }
        }
         $st->execute();
         return $st;
    }

Thanks in advance

  • 写回答

1条回答 默认 最新

  • duan20145 2015-10-14 09:17
    关注

    Nope, this solution is not good. It's inconvenient and error-prone.
    Yes, there is a much better solution for running regular queries:

    Just have your data in array like this

    $array['city']    = $city;
    $array['city_id'] = $city_id;   
    

    and then send it directly to execute():

    $query = "update cities set city=:city where city_id=:city_id";
    $pdo->prepare($query)->execute($array);
    

    which is all the code you need to run this query, no clumsy BindParameters function ever needed.

    As long as you keep PDO::ATTR_EMULATE_PREPARES as false, this approach won't make any trouble for you.

    For the regular SQL query you never need neither bindParam() nor it's third parameter.

    So, make this function as this

    function run($query, $array = NULL) {
    
        $st = $this->dbc->prepare($query);   
        $st->execute($array);
        return $st;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 VS2022创建MVC framework提示:预安装的程序包具有对缺少的注册表值的引用
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用
  • ¥20 51单片机学习中的问题
  • ¥30 Windows Server 2016利用兩張網卡處理兩個不同網絡
  • ¥15 Python中knn问题
  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库