不在所选的特定单选按钮上显示其他结果

时间:2014-07-30 09:11:47

标签: php mysql database mysqli

使用4单选按钮作为选项,选择付款列以汇总所有号码。我写了如果select等于第一个然后运行第一个查询,如果它是第二个运行第二个查询。即使我选择第二个,它也会显示在第一笔付款上。是因为我在代码末尾的回声?有人可以帮忙吗?应该使用for

HTML编码(paycal.html):

<body>
<form name="input" action="paycal.php" method="post">
<fieldset>
<legend>Which payment do you want to SUM up:</legend>
    <input type="radio" name="payment" value="first" /> First 
    <input type="radio" name="payment" value="second" /> Second
    <input type="radio" name="payment" value="third"  /> Third
    <input type="radio" name="payment" value="fourth"  /> Fourth

</fieldset>
<input type="submit" value="Submit" />   
</form>
</body>
</html>

PHP编码(paycal.php):

<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);


$pay=$_REQUEST['payment']; 

// MySQL database connection, username, password, database name
$con=mysqli_connect("localhost","username","password","database_name");

// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

if ($pay=="first") $query="SELECT *, SUM(first_payment) FROM `Customer Information`";
else if ($pay=="second") $query="SELECT *, SUM(second_payment) FROM `Customer Information`";
else if ($pay=="third") $query="SELECT *, SUM(third_payment) FROM `Customer Information`";
else if ($pay=="fourth") $query="SELECT *, SUM(fourth_payment) FROM `Customer Information`";


$result = mysqli_query($query);

// Executing and error checking of query
if (!mysqli_query($con,$query)) {
  die('Error: ' . mysqli_error($con));
}

while($row = mysqli_fetch_array($result)) {

 echo $row['first_payment'];
}

// Close MySQL
mysqli_close($con);
?>

2 个答案:

答案 0 :(得分:1)

您想要显示什么:

 echo $row['first_payment'];

如果要显示不同的结果,则必须切换列。

switch($pay)
{
   case "first":
      echo $row['first_payment'];
      break;
   case "second":
      echo $row['second_payment'];
      break;
   case "third":
      echo $row['third_payment'];
      break;
   case "fourth":
      echo $row['fourth_payment'];
      break;
   default:
      echo "nothing selected";
}

OR:

将你的sql调整为:

SELECT SUM(first) as paymentSum From ...

并使用它

echo $row['paymentSum'];

答案 1 :(得分:1)

while($row = mysqli_fetch_array($result)) {
    echo $row[$pay.'_payment'];
}

只需使用您使用的变量($pay

使密钥生成动态

在其他想法中,这是非常糟糕的桌面设计。如果你有更好的设计,你就不会遇到这样的问题。我建议你改变它。