PHP functions and if/else statements
I am trying to write a script that includes if/else statements and functions. some background
$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)
if all three of theses requirements are met then it should say "data accepted" if something is not met (one or all) th开发者_JS百科e "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";}
?>
The second if should be if($de==1)
$de=1
will always return true.
Also add semicolons after each statement.
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";
}
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
$parts = $_POST["parts"];
$desc = $_POST["desc"];
$price = $_POST["price"];
<?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>';
}
?>
精彩评论