PHP: problema extraño con los datos POST

I'm coding out a simple contact form, and the following code is giving me trouble:

if(!strlen($_POST['lastname']) > 0){
    echo '<p class="message error">Please enter the parent\'s last name.</p>';
}

if(!strlen($_POST['comments']) > 5){
    echo '<p class="message error">Please tell us a little more in the comments field.</p>';
}

Relevant form element:

<textarea name="comments" cols="60" rows="5"><?=(isset($_POST['comments']) ? $_POST['comments'] : '')?></textarea>

When I leave both fields blank, only the first error message (along with the others not shown) displays, whereas the one for the comments field does not.

The error checking even returns with an error if I submit the comments fields with less than 5 characters, as it should, but the error message does not print. In addition, I even echoed the strlen() of the comments field when I submitted with it blank and it prints out 0.

Can anyone see what the problem here is?

preguntado el 01 de febrero de 12 a las 04:02

Why not use if(strlen($_POST['comments']) < 6){ - it reads better. -

@Kieran Andrews - Because I'm 2 hours into overtime tonight, that's why, hehe... But thanks for that. Repost as answer please. -

Caso clásico de don't drink and codeo don't get tired and code. : o) -

4 Respuestas

if (!strlen > 0) primero evalúa strlen, which gives, say, 10. This is then negated by ! a false. Este planteamiento de « luego se compara con > 0, cual es false, Desde false will be cast to 0 y 0 > 0 is false. The other way around, if the string is actually empty, the condition will be true.

Tu quieres if (!(strlen > 0)) or if (strlen <= 0).

Respondido 01 Feb 12, 08:02

¿Falta paréntesis?

if(!(strlen($_POST['lastname']) > 0)) {
    echo '<p class="message error">Please enter the parent\'s last name.</p>';
}

if(!(strlen($_POST['comments']) > 5)) {
    echo '<p class="message error">Please tell us a little more in the comments field.</p>';
}

Respondido 01 Feb 12, 08:02

Tied with deceze... Thank you! - AVProgrammer

If you want to validate the data whether it is entered you can use following options too

if(empty($_POST['name'])){
  echo 'Enter Name';
}

or

if(trim($_POST['name'])==''){
 echo 'Enter Name';
}

Respondido 01 Feb 12, 08:02

Just to be clear, the problem here is that the ! applies to the return value from strlen only and not the entire comparison expression. The above if statements will Siempre hay falso retorno.

It could be rewritten like this to work:

if (!(strlen($_POST['lastname']) > 0)){ /* display error */ }

This is because the ! negates the result of the expression nested in parentheses and not the number returned by strlen.

Also, I would recommend not returning the POSTed value unaltered in the HTML source, that's just asking for trouble...

Respondido 01 Feb 12, 08:02

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.