TBP
TBP

Reputation: 23

PHP functions and if/else statements

I am trying to write a script that includes if/else statements and functions. some background

if all three of theses requirements are met then it should say "data accepted" if something is not met (one or all) the "Invalid...." needs to show.

can someone tell me what part of my script I should look at.

<?php
$parts = $_POST["parts"];
$desc  = $_POST["desc"];
$price = $_POST["price"];

$pa = substr($parts, 0, 1);
$de = strlen($desc);

if ($pa != "N")
 {echo "Invalid Part Number";}
else
 if ($de <= 1)
  {echo "Invalid Description Length";}
 else
  if ($price <= 0)
   {echo "Invalid Price";}
    else
     {echo "Data Accepted";}
?>

Upvotes: 1

Views: 3169

Answers (5)

Joey
Joey

Reputation: 51

    <?php
    $parts = '';
    $desc = '';
    $price = 0;
    if ($_POST['parts'] != 'n')
    {
    echo 'Not equal to n<br>';
    }
    else {
    'Accepted input<br>';
    }
    $desc = strlen($_POST['desc']);
    if ($desc < 1)
    {
    echo 'Input less than 1<br>';
     }
    else {
    echo 'Accepted input<br>';
    }
    if ($_POST['price'] < 0)
    {
    echo 'Input below 0<br>';
    }
    else {
    echo 'Input accepted<br>';
    }
    ?>

Upvotes: 0

Mukesh Chapagain
Mukesh Chapagain

Reputation: 25958

Your requirement:-

$parts first character should have the letter "N"

$desc is suppose to be at least one character long

$price needs to be positive (0 or higher)

Solution:-

$parts = $_POST["parts"];
$desc  = $_POST["desc"];
$price = $_POST["price"];

$pa = substr($parts, 0, 1);
$de = strlen($desc);

if($pa != 'N') {
    echo "Invalid Part Number";
} elseif($de < 1) {
    echo "Invalid Description Length";
} elseif($price < 0) {
    echo "Invalid Price";
} else {
    echo "Data Accepted";
}

Upvotes: 2

1ftw1
1ftw1

Reputation: 666

the second if should be if($de < 1) you can have if($de == 1) if its always going to be one character long but this will work if its 1 or more

Upvotes: 1

Dejan Marjanović
Dejan Marjanović

Reputation: 19380

$parts = $_POST["parts"];
$desc  = $_POST["desc"];
$price = $_POST["price"];

Upvotes: 0

Rasika
Rasika

Reputation: 1998

The second if should be if($de==1) $de=1 will always return true.

Also add semicolons after each statement.

Upvotes: 2

Related Questions