为什么不存储变量?

时间:2014-09-04 05:06:31

标签: php

好的,正如你在代码中看到的那样,我试图添加总数..我之前使用过一个while()之外的变量,但不是这样。所以,如果有人能指出我正确的方向?我知道我需要使表单工作,这不是问题。我的格式很糟糕,但这不是问题,所以请不要对它进行评论。

<?php
require 'core/config.php';
?>
<form onsubmit="sendToServer();">
CPU <select id="proc">
<?php
$cpuPrice = "";
$query = $con->query("SELECT * FROM partslist WHERE Category = 'CPU'");
while($row = $query->fetch_array(MYSQLI_BOTH))
{
    $cpuPrice .= $row['ProductPrice'];
    echo '<option value="'.$row['ProductName'].'">'.$row['ProductName'].' - '.$row['ProductPrice'].'</option>'; 
}
?>
</select><br>

RAM <select id="proc1">
<?php
$ramPrice = "";
$query = $con->query("SELECT * FROM partslist WHERE Category = 'RAM'");
while($row = $query->fetch_array(MYSQLI_BOTH))
{
    $ramPrice .= $row['ProductPrice'];
    echo '<option value="'.$row['ProductName'].'">'.$row['ProductName'].' - '.$row['ProductPrice'].'</option>'; 
}
?>
</select><br>

GPU <select id="proc2">
<?php
$gpuPrice = "";
$query = $con->query("SELECT * FROM partslist WHERE Category = 'GPU'");
while($row = $query->fetch_array(MYSQLI_BOTH))
{
    $gpuPrice .= $row['ProductPrice'];
    echo '<option value="'.$row['ProductName'].'">'.$row['ProductName'].' - '.$row['ProductPrice'].'</option>'; 
}
?>
</select><br>

HDD <select id="proc3">
<?php
$hddPrice = "";
$query = $con->query("SELECT * FROM partslist WHERE Category = 'HDD'");
while($row = $query->fetch_array(MYSQLI_BOTH))
{
    $hddPrice .= $row['ProductPrice'];
    echo '<option value="'.$row['ProductName'].'">'.$row['ProductName'].' - '.$row['ProductPrice'].'</option>'; 
}
?>
</select><br>

SSD <select id="proc4">
<?php
$ssdPrice = "";
$query = $con->query("SELECT * FROM partslist WHERE Category = 'SSD'");
while($row = $query->fetch_array(MYSQLI_BOTH))
{
    $ssdPrice .= $row['ProductPrice'];
    echo '<option value="'.$row['ProductName'].'">'.$row['ProductName'].' - '.$row['ProductPrice'].'</option>'; 
}

$total = $cpuPrice + $ramPrice + $gpuPrice + $hddPrice + $ssdPrice;
?>
</select><br><br>

<button type="submit">Build</button>
</form>
<div style="border:1px;border-color:black;">Total: $<?php echo $total; ?></div>

编辑 - 更深入.. 我需要的是显示总数,但它是空的..

1 个答案:

答案 0 :(得分:1)

尝试在查询中进行数学运算,例如:

CPU <select id="proc">
<?php
$cpuPrice = 0;
$query = $con->query("SELECT *, (SUM(ProductPrice)) as CpuPrice FROM partslist WHERE Category = 'CPU'");
while($row = $query->fetch_array(MYSQLI_BOTH))
{
    $cpuPrice = $row['CpuPrice '];
    echo '<option value="'.$row['ProductName'].'">'.$row['ProductName'].' - '.$row['ProductPrice'].'</option>'; 
}
echo 'cpuPrice'.$cpuPrice;
?>
</select><br>