updating mysql records based on option selection
Hello I cannot figure out what is wrong w开发者_开发知识库ith my code. Have not much experience with php yet. Can someone please tell me what am I doing wrong??
Here is my code:
<?php
include 'mysql_connect.php';
if (!isset($_POST['submit'])) {
$fuelQuery2 = sprintf("UPDATE fuel_price SET `Price` = '%s' WHERE FuelType = '%s' LIMIT 1",
mysql_real_escape_string($_POST['inputPrice']),
mysql_real_escape_string($_POST['fueltype']));
$Result = mysql_query($fuelQuery2);
if($Result){
echo 'Price has been updated!';
} else{
echo 'Failed to update price!';
}
} else{
echo 'No form submitted';
}
?>
<h1>Update Oil Price</h1>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Oil Price:<input name="inputPrice" type="text" value=""/>
Product
<select name="fueltype">
<option value="Oil">Kero</option>
<option value="Diesel">Diesel</option>
<option value="RedDiesel">Red Diesel</option>
</select>
<input type="submit" name="submit" value="Modify" />
</form>
It's really simple, change
if (!isset($_POST['submit'])) {
to
if(isset($_POST['submit'])) { //Only execute the query when the form is submitted
Your original code told PHP to execute the query when the form wasn't submitted (notice that I removed the !) instead of when it was. The notices you were getting were telling you that the $_POST
variables you grabbed for your query didn't exist (because the code ran before the form was submitted).
Also, do look into PDO. The mysql_
family of functions is no longer the preferred method for interacting with the database layer.
PHP
In mysql_connect.php
please ensure that you call mysql_connect()
and mysql_select_db()
.
Then you can adjust your code to the following:
<?php
include 'mysql_connect.php';
if ('POST' == $_SERVER['REQUEST_METHOD'] and
isset($_POST['fuel_type']) and
isset($_POST['oil_price'])) {
$fuel_type = mysql_real_escape_string($_POST['fuel_type']);
$oil_price = mysql_real_escape_string($_POST['oil_price']);
$SQL = "UPDATE `fuel_price`
SET `Price` = '$oil_price'
WHERE `FuelType` = '$fuel_type'";
if(mysql_query($SQL)) {
echo 'Price updated.';
} else {
echo 'Failed to update.';
}
}
?>
HTML Form
You don't need PHP_SELF
in the action
and you can just leave it blank to submit onto the same page.
<form action="" method="post">
<label for="oil_price">Oil Price</label>
<input name="oil_price" id="oil_price" type="text" value="" />
<label for="fuel_type">Product</label>
<select name="fuel_type" id="fuel_type">
<option value="Oil">Kerosene</option>
<option value="Diesel">Diesel</option>
<option value="RedDiesel">Red Diesel</option>
</select>
<input type="submit" name="submit" value="Modify" />
</form>
精彩评论