문제

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

도움이 되었습니까?

해결책

Try

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

다른 팁

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);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top