获取参数化查询的数组

时间:2015-01-23 16:51:37

标签: php arrays

我需要以这种形式获得一个数组:

array(':name'=>'PRIMO,':time_of_execution'=>12,':price'=>50,':active'=>1))

这是我的开始$cols数组:

Array
(
    [key] => Array
        (
            [0] => name
            [1] => time_of_execution
            [2] => price
            [3] => active
        )

    [value] => Array
        (
            [0] => Array
                (
                    [name] => PRIMO
                    [time_of_execution] => 10
                    [price] => 100
                    [active] => 1
                )

        )

)

$cols['key']我有数据库列,我可以实现基础$sql

$sql = 'INSERT INTO '.$this->table.'('.implode(",", $cols['key']).') VALUES (';
            $i=1;
            foreach ($cols['key'] as $key=>$value)
            {
                $sql.=':'.$value;
                if ($i<count($cols['key']))
                {
                    $sql.=', ';
                }
                $i++;
            }
            $sql.= ')';

现在我遗漏的最后一段代码是以这种形式转换数组中的$cols['value']

array(':name'=>'PRIMO,':time_of_execution'=>12,':price'=>50,':active'=>1))

我的代码,但错误的是:

$max = count($cols['value']);
            $i=0;
            $k=0;
            foreach ($cols['key'] as $key=>$value)
            {
                for($i=0;$i<$max;$i++)
                {
                    $args[$k] = array(':'.$value=>$cols['value'][$i][$value]);
                    $k++;
                }
            }

2 个答案:

答案 0 :(得分:2)

为什么不简单地喜欢这个?

$args = array();
foreach($cols['value'][0] as $key => $value) {
    $args[':'.$key] = $value;
}

如果您真的要使用嵌套插件并需要从$ cols数组中提取多条记录,我可以选择以下内容:

$args = array();
foreach($cols['value'] as $i => $col) {
    $args[$i] = array();
    foreach($col as $key => $value) {
        $args[$i][':'.$key] = $value;
    }
}

答案 1 :(得分:0)

  

此代码将为您设置绑定值和值   陈述(程序):

$set =  array(
    'key' => array(
            '0' => name,
            '1' => time_of_execution,
            '2' => price,
            '3' => active,
        ),

    'value' => array(
            0 => array(
                    'name' => 'PRIMO',
                    'time_of_execution' => 10,
                    'price' => 100,
                    'active' => 1,
                ),

            1 => array(
                    'name' => 'POOP',
                    'time_of_execution' => 20,
                    'price' => 131,
                    'active' => 2
                )

        )

);
        $b  =   1;
        foreach($set['value'] as $row => $values) {
                // loop each instance
                foreach($values as $paramkeys => $params) {
                        // Set bind array/parameters
                        $bind[":".$b]   =   $params;
                        // Save to sql for implosion
                        $sql[$row][]    =   ":".$b;
                        $b++;
                    }
            }

        // Implode each set of values
        foreach($sql as $sets) {
                $sqlcomp[]  =   "(".implode(",",$sets).")";
            }

    // Implode columns to set columns
    $columns    =   "(`".implode("`,`",$set['key'])."`)";

    echo '<pre>';
    print_r($bind);
    print_r($sqlcomp);
    print_r($columns);

会给你:

// Bind array w/parameters
Array
(
    [:1] => PRIMO
    [:2] => 10
    [:3] => 100
    [:4] => 1
    [:5] => POOP
    [:6] => 20
    [:7] => 131
    [:8] => 2
)
// Values
Array
(
    [0] => (:1,:2,:3,:4)
    [1] => (:5,:6,:7,:8)
)
// Columns
(`name`,`time_of_execution`,`price`,`active`)

<强> SQL:

echo 'insert into `table` '.$columns." VALUES ".implode(",",$sqlcomp);

给你:

insert into `table` (`name`,`time_of_execution`,`price`,`active`) VALUES (:1,:2,:3,:4),(:5,:6,:7,:8)
  

由于您使用的是$this->table,因此您可能正在使用此功能   class所以这里是一个类版本:

class   QueryEngine
    {
        public      $columns;
        public      $rows;
        public      $parameters;
        protected   $table;

        public  function SetStatement($array = array())
            {
                $b  =   1;
                foreach($array['value'] as $row => $values) {
                        // loop each instance
                        foreach($values as $paramkeys => $params) {
                                // Set bind array/parameters
                                $bind[":".$b]   =   $params;
                                // Save to sql for implosion
                                $sql[$row][]    =   ":".$b;
                                $b++;
                            }
                    }

                // Implode each set of values
                foreach($sql as $sets) {
                        $sqlcomp[]  =   "(".implode(",",$sets).")";
                    }

                // Bound Parameters
                $this->parameters   =   $bind;
                // Row array
                $this->rows         =   $sqlcomp;
                // Implode columns to set columns
                $this->columns      =   "(`".implode("`,`",$array['key'])."`)";

                $this->AssembleSQL();

                return $this;
            }

        public  function AssembleSQL()
            {
                $this->statement[]  =   '`'.$this->table.'` '.$this->columns.' VALUES '.implode(",",$this->rows);
                return $this;
            }

        public  function insert($table = false)
            {
                $this->table        =   $table;
                $this->statement[]  =   "insert into ";
                return $this;
            }
    }

// New instance
$QueryEngine    =   new QueryEngine();
// Returned array of compiled elements, so implode
$statement      =   implode("",$QueryEngine->insert('mytable')->SetStatement($set)->statement);
// Gives you:
// insert into `mytable` (`name`,`time_of_execution`,`price`,`active`) VALUES (:1,:2,:3,:4),(:5,:6,:7,:8)
// Assign parameters
$parameters     =   $QueryEngine->parameters;
// To use in PDO (I am familiar with PDO so I will give that example)
// Insert formatted statement
$query          =   $con->prepare($statement);
// Execute with bound parameters
$query->execute($parameters);