Reputation: 744
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? thanks in advance
Upvotes: 3
Views: 3023
Reputation: 522135
I would not quote-implode strings like this; while it may work, it's hard to read and prone to errors. The correct thing would be to quote each individual entry properly and implode the result merely with commas:
$fields = join(',', array_map(function ($field) { return "`$field`"; }, array_keys($user_data)));
$data = join(',', array_map(function ($value) { return mysql_real_escape_string($value); }, $user_data));
The field names are controlled by you, as such quoting them with a backslash is sufficient. For the user supplied data you need to run it through a proper SQL escaping function or better yet use prepared statements. The above demonstrates the legacy method of using the mysql_ extension, something you really shouldn't be doing anymore these days.
The code should more look like this:
$fields = join(',', array_map(function ($field) { return "`$field`"; }, array_keys($user_data)));
$placeholders = join(',', array_map(function ($field) { return ":$field"; }, array_keys($user_data)));
$stmt = $pdo->prepare("INSERT INTO foo ($fields) VALUES ($placeholders)");
$stmt->execute($user_data);
Upvotes: 0
Reputation: 6344
Try
$user_fields = '`' . implode('`, `', array_keys($user_data)) . '`';
$user_data = "'" . implode("', '", array_values($user_data)) . "'";
Upvotes: 5