phpsql-insertassociative-array

Build a dynamic INSERT query from the keys and values of an associative array


I have a question regarding the implode() in php, I have this array()

$user_data = array(
    'user_id_num' => $_POST['userid'],
    'fullname' => $_POST['userfname'],
    'username' => $_POST['useruname'],
    'password' => $password_hash
);

what I want to achieve is like this for example,

for the fields

`user_id_num`,`fullname`,`username`,`password`

and for the values

'2159','Sample Name','example','mypassword' <- hash password

what I have tried so far is this

$user_fields = '`' . implode('`, `', $user_data) . '`';
$user_data   = '\'' . implode('\', \', $user_data) . '\'';

but I can't get what I want to achieve can someone help me with this?


Solution

  • Community warning: this approach is critically unsafe, because it proposes adding variables - both column names and values - into SQL without any protection.

    Try

    $user_fields = '`' . implode('`, `', array_keys($user_data)) . '`';
    $user_data   = "'" . implode("', '", array_values($user_data)) . "'";