patternphpMinor
Inserting a name into a database table
Viewed 0 times
intodatabasenameinsertingtable
Problem
I want to ask you if my PHP code is safe enough. I don't know if I should escape special characters in string after regex validation:
And what if i use PDO prepare instead of wordpress function?
60) {
$errors[] = "Invalid name";
}
if (empty($errors)) {
echo json_encode(['status' => true]);
$wpdb->query($wpdb->prepare("INSERT INTO people VALUES(null, %s)", $_POST['name']));
} else {
echo json_encode(['status' => false, 'errors' => $errors]);
}And what if i use PDO prepare instead of wordpress function?
Solution
In terms of security, you should be safe from SQL injection since you are using parameterized queries as recommended. That's true whether or not you validate the names using the regex. Do not perform any additional escaping — that would only mangle your data.
That regex is for enforcing your business rules (i.e. you want to reject names written in Cyrillic, names with French accents like é, Irish surnames like O'Something), and has nothing to do with database security.
I do not recommend mixing PDO with the WordPress database API.
The WordPress documentation recommends that you use
In accordance with the WordPress documentation, you should check the return value from
That regex is for enforcing your business rules (i.e. you want to reject names written in Cyrillic, names with French accents like é, Irish surnames like O'Something), and has nothing to do with database security.
I do not recommend mixing PDO with the WordPress database API.
The WordPress documentation recommends that you use
$wpdb->insert() for simple INSERT queries.In accordance with the WordPress documentation, you should check the return value from
$wpdb->query() — a FALSE value indicates failure. You should do that before declaring victory with echo json_encode(['status' => true]);.if (!empty($errors)) {
echo json_encode(['status' => false, 'errors' => $errors]);
} elsif (FALSE === $wpdb->insert('people', ['name' => $_POST['name']], '%s')) {
echo json_encode(['status' => false, 'errors' => ['Database error: ' . $wpdb->last_error]]);
} else {
echo json_encode(['status' => true]);
}Code Snippets
if (!empty($errors)) {
echo json_encode(['status' => false, 'errors' => $errors]);
} elsif (FALSE === $wpdb->insert('people', ['name' => $_POST['name']], '%s')) {
echo json_encode(['status' => false, 'errors' => ['Database error: ' . $wpdb->last_error]]);
} else {
echo json_encode(['status' => true]);
}Context
StackExchange Code Review Q#92894, answer score: 4
Revisions (0)
No revisions yet.