简体   繁体   English

PHP / PDO:Mysql插入功能

[英]PHP/PDO: Mysql insert function

I'm trying to create a pdo mysql query function. 我正在尝试创建pdo mysql查询功能。 This function works just fine if it only takes on array value but if its more than one value, it switches values on the bindParam() part. 如果此函数仅接受数组值,但该函数不止一个值,则该函数在bindParam()部分上切换值就可以正常工作。

public function db_qf($table, $fieldvalues, $where)
{//query function
    $sql = "INSERT INTO " . $table . " (";
    $parameters = "";
    $counter = 0;
    foreach ($fieldvalues as $key => $value)
    {
        $sql .= $key;
        $parameters .= ":" . $key;
        if (++$counter != count($fieldvalues)){$sql .= ", "; $parameters .= ", ";}
    }
    $sql .= ") VALUES (" . $parameters . ") " . $where;
    $this->dbquery = $this->dbh->prepare($sql);
    foreach ($fieldvalues as $key => $value)
    {
        $this->dbquery->bindParam(":" . $key, $value);
    }
    $this->dbquery->execute();
}

So if i call the function with the following parameters it will switch the values so the date will be inserted for the amount and the amount will be inserted for the date. 因此,如果我使用以下参数调用该函数,它将切换值,以便为金额插入日期,为日期插入金额。

$this->db_qf("bills", array("date" => "2013-11-24", "amount" => 30), "");

I can't seem to figure out why this is happening. 我似乎无法弄清楚为什么会这样。

我需要使用bindvalue而不是bindparam来锁定$ value变量的值,而不是对其进行引用,因为$ value变量在每次循环迭代时都会更改值。

I tested and it works: 我测试了并且可以正常工作:

public function insert($table,$columns_and_values) {
            /*
             * Columns Process
             */
            $forms    = [
                    "columns"   => "",
                    "values"    => ""
            ];

            /*
             * Array to execute() method
             */
            $array_to_execute = [];
            foreach($columns_and_values as $key => $val)
            {
                $forms["columns"]   .= "$key,";
                $forms["values"]    .= ":{$key},";


                $array_to_execute[":{$key}"] = $val;
            }
            $forms["columns"] = substr($forms["columns"],0,-1);
            $forms["values"] = substr($forms["values"],0,-1);
            //-----------------End of Columns Process


            $query = sprintf("INSERT INTO $table(%s) VALUES(%s)",$forms['columns'],$forms['values']);
            $stmt = $this->prepare($query);
            $stmt->execute($array_to_execute);
}

By calling the method: 通过调用方法:

<?php
class Database extends PDO {}

$db = new Database();

$cols = [
     'email'      => 'daison12006013@gmail.com',
     'password'   => '1234567890'
];
$db->insert("account",$cols);

Try it! 试试吧!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM