php mysql将数据库值与表单选择相乘

时间:2011-08-29 15:44:51

标签: php mysql calculator

你好,我真的很挣扎。我被要求开发一个计算油价的脚本但不能让它起作用。我已经能够设置一个表格来更新燃油价格。

我有一张叫做fuel_price的桌子。在该表中将是每升燃料的成本,其存储在Price下。例如,如果每升油价为0.50英镑,我需要将此值乘以在表格下拉列表中选择的值。

任何人都可以指导我做我应该做的事情吗?

好的是更新代码预览。

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">

<select name="fueltype">
<option>- Select fuel type -</option>
<option value="Diesel">Diesel</option>
<option value="Red Diesel">Red Diesel</option>
<option value="Home Heating Oil">Home Heating Oil</option>
</select>
<select name="qtylitres">
<option>- Qty in Litres -</option>
<option value="100">100</option>
<option value="200">200</option>
<option value="400">400</option>
<option value="500">500</option>
<option value="900">900</option>
<option value="1000">1000</option>
</select>

<input type="hidden" name="id" value="" />
<input type="submit" name="submit" value="Submit" />
</form>

<?php

include 'mysql_connect.php';

$pdo = '';

    $stmt = $pdo->prepare("SELECT `Oil` from `fuel_price` WHERE id = '1'"); 
    if (!$stmt->execute()) { die($stmt->errorInfo[2]); } 
    $row = $stmt->fetch(); 

    $price = $row['Oil'];

    echo $_POST['qtylitres'] * $price;

?>

任何人都知道我哪里出错了?

谢谢

2 个答案:

答案 0 :(得分:0)

<?php

    //Connect to database here. In this example, I'll assume you connected using PDO
    //Although the same logic applies on any engine.

    $stmt = $pdo->prepare("SELECT `price` from `fuel_price` WHERE `type` = :type"); //Prepare a query
    $stmt->bindValue(':type', $_POST['type']); //Assuming the first <select> is named type
    if (!$stmt->execute()) { die($stmt->errorInfo[2]); } //Display an error and terminate script if query failed.
    $row = $stmt->fetch(); //Assuming you have only one row, fetch should only be called once.

    $price = $row['price'];

    echo $_POST['qtylitres'] * $price; //Multiply quantity with price and print result.

?>

请注意,我没有测试过它,但它应该可以工作。您的标记不完整,缺少第一个<select>的开头。阅读评论,你应该好好去。

答案 1 :(得分:0)

假设您的表中有一个“价格”列,并且唯一的结果包含正确的价格:

include 'mysql_connect.php';
if (isset($_POST['submit'])) {
    // edit: added fueltype in the where clause
    $fueltype = mysql_real_escape_string($_POST['fueltype']);
    $q = "SELECT * FROM fuel_price WHERE id = '1' AND fueltype='$fueltype'";


    $result = mysql_query($q);
    $row= mysql_fetch_array($result);
    $price = $row['price'] * $_POST['qtylitres'];
    echo $price;