Валидация данных в форме с загрузкой их в БД PHP/MySQL
У меня есть две функции и я не могу их правильно скрестить. Как поступить чтобы при условии что данные прошли успешно проверку, они были загружены в БД? Сама по себе функция addComment работает корректно
function addComment(string $name, string $content): void
{
global $pdo;
$sql = "INSERT INTO comments (name, content) VALUES (:name, :content)";
$statement = $pdo->prepare($sql);
$statement->bindParam("name", $name);
$statement->bindParam("content", $content);
$statement->execute();
}
function dataValidation(): void
{
$errorMessage = [];
$name = trim($_POST['name']);
$content = trim($_POST['content']);
$allowedSymbols = "/^[a-zA-Z-' ]*$/";
$nameLength = 30;
$contentLength = 1000;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_SERVER['HTTP_REFERER'] == "http://localhost/comments/index.php")
{
if (mb_strlen($name) > $nameLength) {
$errorMessage['name'] = "Name should have less than 30 symbols";
}
elseif (mb_strlen($content) > $contentLength) {
$errorMessage['content'] = "Commentary should have less than 1000 symbols";
}
elseif (empty($name)) {
$errorMessage['name'] = "Enter your name";
}
elseif (empty($content)) {
$errorMessage['content'] = "Enter your commentary";
}
elseif (!preg_match($allowedSymbols, $name)) {
$errorMessage['name'] = "Only letters and white space allowed";
}
elseif (!preg_match($allowedSymbols, $content)) {
$errorMessage['content'] = "Only letters and white space allowed";
}
}
}
Ответы (1 шт):
Автор решения: phpBear
→ Ссылка
function addComment($pdo, $params ): void
{
$result = false;
if ( is_array( $params ) && count($params) > 0 && is_array(array_keys($params)) && count(array_keys($params)) > 0 ) {
$sql = "INSERT INTO comments (name, content) VALUES (:name, :content)";
if ( $sth = $pdo->prepare($sql) ) {
foreach( array_keys($params) as $key => $value ) {
$sth->bindParam( $key, $value);
}
$result = $sth->execute();
}
}
return $result;
}
function dataValidation()
{
$errorMessage = [];
if ( isset($_POST) && is_array($_POST) && count($_POST) > 0 && $_SERVER['HTTP_REFERER'] == "http://localhost/comments/index.php")
{
foreach(['name', 'content'] as $fieldName ) {
if ( isset($_POST[ $fieldName ]) && trim($_POST[ $fieldName ]) != '' ) {
$maxLength = ( $fieldName != 'name' ? 1000 : 30 );
if ( mb_strlen(trim($_POST[ $fieldName ])) > $maxLength ) {
if (!preg_match( "/^[a-zA-Z-' ]*$/", $_POST[ $fieldName ])) {
$errorMessage[ $fieldName ] = "Only letters and white space allowed";
}
} else { $errorMessage[ $fieldName ] = ucfirst( $fieldName )." should have less than ".$maxLength." symbols"; }
} else { $errorMessage[ $fieldName ] = "Enter your ".( $fieldName != 'name' ? 'commentary' : $fieldName ); }
}
}
return $errorMessage;
}
if ( doValidation() && addComment( $pdo, $_POST ) ) {
//Все отлично!
}