简体   繁体   中英

PHP/PDO: Mysql insert function

I'm trying to create a pdo mysql query function. 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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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