menu

arrow_back Where is the error in php code?

by
0 votes
Dear Gurus!
Taking the first steps to learn PHP - write calulator.
The first task set is to check the existence of data coming from forms. I.e. if any field is left blank, display a message below the form - "something not given!"
The script is written, but the message does not appear. Where did I go wrong?

<form action='calc.php' method="post">
<label>Число 1:</label>
<br />
<input name='num1' type='text' />
<br />
<label>Оператор: </label>
<br />
<label for="operator">
<select name="operator" id="operator">
<option value="+">+</option>
<option value="-">-</option>
</select>
<br />
<label>Число 2: </label>
<br />
<input name='num2' type='text' />
<br />
<br />
<input type='submit' value='Считать'>
</form>
<br />
<br />
<?php

$num1 = int($_POST['num1']);
$num2 = int($_POST['num2']);

if (empty($num1 or $num2)) {
echo "Что-то не передано!";
}

?>

4 Answers

by
0 votes
Did the option to display the message under the field that is not filled:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$require = ['num1', 'num2']; //поля которые надо заполнить.
$errors[] = ''; //массив в котором сохраним ошибки

foreach($require as $key) {
if(empty($_POST[$key])) {
$errors[$key] = 'Это поле надо заполнить!';
}
}
}
?>

<form action='calc.php' method="post">
<label>Число 1:</label>
<br />
<input name='num1' type='text' />
<?php
$msg = isset($errors['num1']) ? "Введите первое число" : "";
echo $msg;
?>
<br />
<label>Оператор: </label>
<br />
<label for="operator">
<select name="operator" id="operator">
<option value="+">+</option>
<option value="-">-</option>
</select>
<br />
<label>Число 2: </label>
<br />
<input name='num2' type='text' />
<?php
$msg = isset($errors['num2']) ? "Введите первое число" : "";
echo $msg;
?>
<br />
<br />
<input type='submit' value='Считать'>
</form>
<br />
<br />
<?php
if (count($errors) > 0) {
echo 'Заполните все поля!';
}
?>

Сначала проверим, была ли отправлена форма, а потом проверяем заполнены ли все обязательные поля из формы.
by
0 votes
It is specifically for your piece of code. Ideally, you need to watch everything and rewrite from scratch.
<?php

$num1 = intval(isset($_POST['num1']) ? $_POST['num1'] : 0);
$num2 = intval(isset($_POST['num2']) ? $_POST['num2'] : 0);

if (empty($num1) || empty($num2)) {
echo "Что-то не передано!";
}

?>

1 comment

When you open the form ( without sending the data through the form) it appears a message that "something not given!", although this message should appear when I pressed the pedal sabmit, and sent only one number of the two.
Where could be the problem?
by
1 vote
1. Since php 5.5 as You did, but for earlier versions, and empty must be a variable, not an expression, so depending on the php version, maybe worth a try
if (empty($num1) || empty($num2)) {
2. You are not true bring the data to integer
$num1 = int($_POST['num1']); // не верно
$num1 = (int) $_POST['num1']; //верно

2 Comments

0ldn0mad the problem , as it should be, but if You don't need to withdraw, you should check for the existence of a post request.
if(isset($_POST)){
$num1 = int() $_POST['num1'];
// и так далее

Кстати если бы Вы включили вывод всех ошибок, что я крайне рекомендую сделать, особенно пока изучаете php. Вы бы уже увидели эту проблем в виде ошибки. И вообще при error_all меньше "почему так".
When you open the form ( without sending the data through the form) it appears a message that "something not given!", although this message should appear when I pressed the pedal sabmit, and sent only one number of the two.
Where could be the problem?
by
2 votes
if (isset($_POST['num1']) && isset($_POST['num2']) && isset($_POST['operator'])) {
$num1 = intval($_POST['num1']);
$num2 = intval($_POST['num2']);
$operator = $_POST['operator'];

switch ($operator) {
case '+':
echo $num1 + $num2;
break;
case '-':
echo $num1 - $num2;
break;
}

} else {
echo "Что-то не передано!";
}

4 Comments

0ldn0mad ,
because when we just print the form, we check the $_POST, it is empty, so a message is displayed.
Wrap the whole if else in extra
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// …
}


Тем самым, мы будем проверять $_POST и вычислять, только если пользователь нажал на Отправить, а не всегда.
Yan-s ,
Well, what makes You think that is broken? All very excellent! =)
When you open the form ( without sending the data through the form) it appears a message that "something not given!", although this message should appear when I pressed the pedal sabmit, and sent only one number of the two.
Where could be the problem?
all the training the man broke off