我希望你能解决我的问题。我的验证表单的脚本(检查文本框是否为空,如果是数字;注意:在我的区域中,我们使用十进制数字逗号而不是点,PHP仅适用于小数点)不能正常工作。 HTML:
...
<form action="http://localhost/kalkulacka.php" method="post" name="formular">
<table>
<tr>
<td>1 dávka(g):</td>
<td><input type="text" name="davka" maxlength="7" size="7"></td>
</tr>
<tr>
<td>Bielkoviny v 1 dávke(g):</td>
<td><input type="text" name="bielkoviny" maxlength="7" size="7"></td>
</tr>
<tr>
<td>Sacharidy v 1 dávke(g):</td>
<td><input type="text" name="sacharidy" maxlength="7" size="7"></td>
</tr>
<tr>
<td>Balenie(g):</td>
<td><input type="text" name="balenie" maxlength="7" size="7"></td>
<tr>
<td>Cena za balenie(€):</td>
<td><input type="text" name="cena" maxlength="7" size="7"></td>
</tr>
<tr>
<td><input type="submit" value="Vypočítaj"></td>
</tr>
</table>
</form>
PHP:
<?php
$davka=$_POST['davka'];
$bielkoviny=$_POST['bielkoviny'];
$sacharidy=$_POST['sacharidy'];
$balenie=$_POST['balenie'];
$cena=$_POST['cena'];
$is_valid=true;
function vypocitaj($serving, $proteins, $pack, $price)
{
$proteins_percentage=($proteins/$serving)*100;
$price_per_gram=$price/($pack/100*$proteins_percentage);
printf("1 gram bielkoviny stoji: %.3f", $price_per_gram);
}
if (empty($davka)||empty($bielkoviny)||empty($sacharidy)||empty($balenie)||empty($cena))
{
echo "Some boxes are empty!";
$is_valid=false;
}
else /*when I remove this whole "else" block, script at least verifies if are boxes empty by if statement above, but when I add this block, it not even verifies if are boxes empty*/
{
if (!is_numeric($davka))
{
$davka=str_replace(",", ".", $davka);
if (!is_numeric($davka)
{
$is_valid=false;
}
}
if ($is_valid==true && !is_numeric($bielkoviny))
{
$bielkoviny=str_replace(",", ".", $bielkoviny);
if (!is_numeric($bielkoviny)
{
$is_valid=false;
}
}
if ($is_valid==true && !is_numeric($sacharidy))
{
$sacharidy=str_replace(",", ".", $sacharidy);
if (!is_numeric($sacharidy)
{
$is_valid=false;
}
}
if ($is_valid==true && !is_numeric($balenie))
{
$balenie=str_replace(",", ".", $balenie);
if (!is_numeric($balenie)
{
$is_valid=false;
}
}
if ($is_valid==true && !is_numeric($cena))
{
$cena=str_replace(",", ".", $cena);
if (!is_numeric($cena)
{
$is_valid=false;
}
}
if ($is_valid)
{
vypocitaj($davka, $bielkoviny, $balenie, $cena);
}
else
{
echo "Only number are accepted!";
}
}
?>
用JavaScript语法编写的相同脚本在JavaScript中正常工作,但在PHP中不起作用。当我删除主“else”语句时,主“if”语句有效,但是当我添加它时,整个代码都不起作用。当我单独尝试每个功能时 - 他们工作了。
我在这里停留了好几天,我无法动弹。我想知道它不能正常工作的原因。我很感激任何建议。谢谢 ;) 抱歉我的英文。
答案 0 :(得分:2)
我只是将该代码粘贴到我的IDE中,它告诉我有一个缺少的结束括号:
if (!is_numeric($davka))
{
$davka=str_replace(",", ".", $davka);
if (!is_numeric($davka)
// ^ missing brace here
{
$is_valid=false;
}
}
......应该是:
if (!is_numeric($davka))
{
$davka=str_replace(",", ".", $davka);
if (!is_numeric($davka))
{
$is_valid=false;
}
}
如果这样可以解决问题,请使用带语法高亮显示的编辑器......