Inserting a name into a database table 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:

&lt;?php

require_once '../../../wp-load.php';

$errors = [];

if (preg_match('/[^a-ząćęółśżźń ]/i', $_POST['name']) || strlen(trim($_POST['name'])) == 0 || strlen($_POST['name']) &gt; 60) {
    $errors[] = "Invalid name";
}

if (empty($errors)) {
    echo json_encode(['status' =&gt; true]);
    $wpdb-&gt;query($wpdb-&gt;prepare("INSERT INTO people VALUES(null, %s)", $_POST['name']));
} else {
    echo json_encode(['status' =&gt; false, 'errors' =&gt; $errors]);
}


And what if i use PDO prepare instead of wordpress function?
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 $wpdb-&gt;insert() for simple INSERT queries.

In accordance with the WordPress documentation, you should check the return value from $wpdb-&gt;query() — a FALSE value indicates failure.  You should do that before declaring victory with echo json_encode(['status' =&gt; true]);.

if (!empty($errors)) {
    echo json_encode(['status' =&gt; false, 'errors' =&gt; $errors]);
} elsif (FALSE === $wpdb-&gt;insert('people', ['name' =&gt; $_POST['name']], '%s')) {
    echo json_encode(['status' =&gt; false, 'errors' =&gt; ['Database error: ' . $wpdb-&gt;last_error]]);
} else {
    echo json_encode(['status' =&gt; true]);
}