PHP MySQL UPDATE查询不从文本框中发布值

时间:2017-04-21 11:51:31

标签: php mysql ajax

我有一个表单,其中包含从数据库填充的选择列表。执行查询时,将返回成功消息,但不会更新数据库。

以下是表格:

 <form id="formPrice">
 <?php
 $conn = new mysqli('localhost', 'something', 'something', 'something') 
or die ('Cannot connect to db');
$result = $conn->query("SELECT PlotNumber FROM Developments WHERE Development = 'GREENGRAVES' AND Price = 'BOOKED'");
echo "<select name='plot_update'>";
while ($row = $result->fetch_assoc()) {
       echo "<option value=\"Plot\">" . $row['PlotNumber'] . "
</option>";
}
echo "</select>";
?>
<input name="price" type="text" id="price">
<input name="update" type="submit" class="update_price">
</form>

这是ajax请求:

 $('.update_price').click(function() {
 var FormData = $('form').serialize(); 
 $.ajax({
    type: "POST",
    url: '../php/update_price.php',
    data : FormData,
    success:function(html){
        document.getElementById("result_two").innerHTML=html;   
    }  
 });
 return false;
 });

这是php

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} 
$price = $_POST['price'];
$plot = $_POST['plot'];
$sql = "UPDATE Developments SET Price = '".$price."' WHERE PlotNumber = '".$plot."' ";

if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}

$conn->close();

页面在结果div中显示“记录已成功更新”,但数据库条目保持不变。有什么想法吗?我很难过。

2 个答案:

答案 0 :(得分:0)

错误似乎是前端形式的这一行:

echo "<option value=\"Plot\">" . $row['PlotNumber'] . "</option>";

当我改为:

echo "<option>" . $row['PlotNumber'] . "</option>";

有效!

答案 1 :(得分:0)

php脚本下的表单字段存在问题:

将您的php脚本更改为以下内容:

<form id="formPrice">
<?php
$conn = new mysqli('localhost', 'something', 'something', 'something')
or die ('Cannot connect to db');
$result = $conn->query("SELECT PlotNumber FROM Developments WHERE Development = 'GREENGRAVES' AND Price = 'BOOKED'");
echo "<select name='plot'>";
while ($row = $result->fetch_assoc()) {
    echo "<option value=" . $row['PlotNumber'] . ">" . $row['PlotNumber'] . "</option>";
}
echo "</select>";
?>
<input name="price" type="text" id="price">
<input name="update" type="button" class="update_price">

始终确保 - 选择选项值需要具有记录的实际值,并且选择字段将具有表单字段名称。