php mysql multiply database value with form selection
Hello I am really struggling with this. I was asked to develop a script to calculate oil price but cannot get it to work. I have been able to setup a form to update fuel price.
I have a table called fuel_price. In this table will be cost per litre of fuel which is stored under Price. For example if oil price per litre is £0.50 I need to multiply this value by value selected within form dropdown.
Can anyone please guide me on what I am supposed to do??
Ok heres an update code preview.
<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 O开发者_JAVA百科il">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;
?>
Anyone know where I am going wrong??
Thanks
<?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.
?>
Note that I have not tested it, but it should work. Your markup is incomplete, it lacks the opening for the first <select>
. Read the comments and you should be good to go.
assuming that you have a column 'price' in your table, and that the only result contains the correct price:
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;
精彩评论