您好我无法弄清楚我的代码有什么问题。还没有太多的PHP经验。有人可以告诉我,我做错了什么?
这是我的代码:
<?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>
答案 0 :(得分:2)
这很简单,改变
if (!isset($_POST['submit'])) {
到
if(isset($_POST['submit'])) { //Only execute the query when the form is submitted
您的原始代码告诉PHP在未提交表单时执行查询(请注意我删除了!)而不是在何时提交。您收到的通知告诉您,您为查询抓取的$_POST
变量不存在(因为代码在提交表单之前运行)。
另外,请查看PDO。 mysql_
函数族不再是与数据库层交互的首选方法。
答案 1 :(得分:1)
在mysql_connect.php
中,请确保致电mysql_connect()
和mysql_select_db()
。
然后您可以将代码调整为以下内容:
<?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.';
}
}
?>
PHP_SELF
中不需要action
,您可以将其留空以提交到同一页面。
<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>