0

我有这个功能

protected function insert($data){
        $data['datecreated'] = date('Y-m-d h:i:s');
        echo "array_keys(data) = ".$data['datecreated'];
        var_dump($data);
        echo array_keys($data);
        $sql = "INSERT INTO {$this->table_name} (".  array_keys($data).")"; 
        $sql.= " VALUES ('";
        $sql.=implode("','", $data);
        $sql.=")";
        $this->execute($sql);
        $this->last_id = mysql_insert_id();
    }

当我读到array_keys($data)它返回“数组”而不是我这样称呼它的键时,$this->insert(array());为什么会这样?编辑:这是输出

array_keys(data) = 2012-05-18 04:44:46array(2) { [0]=> array(0) { } ["datecreated"]=> string(19) "2012-05-18 04:44:46" } Array
Notice: Array to string conversion in /Applications/MAMP/htdocs/Tamara/model/dbTable.php on line 105
INSERT INTO account (Array) VALUES ('Array','2012-05-18 04:44:46)You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''2012-05-18 04:44:46)' at line 1
4

2 回答 2

5

array_keys 返回一个包含所有键的数组。你也需要内爆

implode(',', array_keys($data));

编辑:你可能想看看这部分

$sql.=implode("','", $data);
$sql.=")";

您需要一个起始和尾随'.

于 2012-05-18T13:49:05.423 回答
1

你想要的是implode(',', array_keys($data))因为array_keys()返回一个包含所有键的数组 - 但你想要一个逗号分隔的字符串:

$sql = "INSERT INTO {$this->table_name} (".implode(',', array_keys($data)).")"; 

顺便说一句,我希望里面的值$data已经被转义了。如果不是,请替换implode("','", $data)implode("','", array_map('mysql_real_escape_string', $data))

于 2012-05-18T13:48:36.247 回答