使用array_keys()进行插入

时间:2016-04-25 19:20:22

标签: php mysql

使用此解决方案Insert array into MySQL database with PHP将数组插入数据库会产生MySql错误。

我的代码:

def handle_login(self):
    """ Handles the login event received after login. """
    self.get_logged_in_user(self.set_logged_in_user)

def set_logged_in_user(self, user_data):
    """ Callback function for handle_login; get_logged_in_user"""
    # Parse received data about logged in user
    self.logged_in_user = json.loads(safe_decode(user_data.readAll().data()))

    # If user had any pending requests from previous login, execute them now
    for (user_id, request) in self.pending_requests.values():
        if user_id == self.logged_in_user['data']['id']:
            request()
    self.pending_requests = {}

代码输出:

// Create arrays and values
        $columns = "`".implode("`, `",array_keys($value))."`";
        $escaped_values = array_map('mysql_real_escape_string', array_values($value));
        $values  = implode("', '", $escaped_values);
        // Print arrays and values
        echo "<br><h4>Columns:</h4> <br>";
        echo $columns;
        echo "<br><h4>Values:</h4><br>";
        echo $values;
        echo "<br><h4>";
        // Insert or update
        $insert = mysql_query("INSERT INTO stocklink2 ($columns) VALUES ('$values') ON DUPLICATE KEY UPDATE ($columns) = ('$values'); ");
        if($insert === FALSE) { 
            die(mysql_errno($link).mysql_error()); // TODO: better error handling
        }
        echo "</h4>";

“Upper”列是一个保留字,所以我必须转义列名。这在我更新单个字段时起作用,但不适用于字段数组。

1 个答案:

答案 0 :(得分:1)

这是错误的:

ON DUPLICATE KEY UPDATE ($columns) = ('$values'); ");
                          ^^^^^^^^^^^^^^^^^^^^^

你正在建设

on duplicate key update (field, field, field, etc..) = (value, value value, ...)

您可以 NOT 并行更新/分配值。你必须做个人

on duplicate key update field1=value1, field2=value2, etc...