如何使用php和mysqli使用HTML表单更新数据库中的记录

时间:2015-02-20 18:41:52

标签: php html mysqli phpmyadmin

我的HTML带有文本框和选择框。我希望用户从下拉选择框中选择一个固定号码,该号码从我的数据库中选取号码。然后,我希望用户在文本框中输入新的月租金。一旦用户点击提交按钮,我希望它根据已选择的单位数更新数据库月租。我可以从数据库中获取统一号码,但似乎无法从文本框中获取信息并在数据库中进行更改。

这是我的代码

Changeback.php(后端)



<?php
include "connect.php";
if(isset($_POST['MonthlyRent'])){
$MonthlyRent = $_POST['MonthlyRent'];
$FlatCode = $_POST['FlatCode'];

$query = "UPDATE MonthlyRent set MonthlyRent = ($MonthlyRent) where FlatCode = ($FlatCode) ";

mysqli_query($con, $query) or die ("Invalid query");
$numrows = mysqli_affected_rows($con);
echo "number of affected rows is " . $numrows;
exit( print_r( $_POST ) );
mysqli_close($con);

}
?>
&#13;
&#13;
&#13;

change.php(前端)

&#13;
&#13;
<html><head><title>Connect to Database</title></head><body> 

<font size="4"> Enter owner details</font><br><br> 
<form action="changeback.php" method="post" >


Monthly Rent <input  type="text" name="MonthlyRent">
Flat Code <select name="FlatCode">

<?php 
$con = mysqli_connect("localhost", "root", "root") or die ("No connection"); 
mysqli_select_db($con , "flat") or die ("db will not open"); 

$query = "SELECT distinct FlatCode from FLAT"; 

$result = mysqli_query($con, $query) or die("Invalid query");  
while($rows = mysqli_fetch_array($result)) { 
      echo "<option value=\"" . $rows[0] . "\">" . $rows[0] . "</option>"; 
}

echo "</select>"; 
 mysqli_close($con);


 ?>
<input type="submit" value="Submit Value"> 
</form></body></html> 
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

问题出在您的UPDATE语句中,您(1)已将MonthlyRent列名放在FLAT表名称所在的位置,以及(2)未在单位周围放置引号代码值。

变化:

$query = "UPDATE MonthlyRent set MonthlyRent = ($MonthlyRent) where FlatCode = ($FlatCode) ";

要:

// Always escape user input to reduce risk of errors and security holes
$escapedMonthlyRent = mysqli_real_escape_string($con, $MonthlyRent);
$escapedFlatCode    = mysqli_real_escape_string($con, $FlatCode);

$query = "update FLAT set MonthlyRent = '$escapedMonthlyRent' "
    ."where FlatCode = '$escapedFlatCode'";

答案 1 :(得分:0)

这不是一个答案,只是一个长篇评论。

如果您有时间(几个小时),我强烈建议您前往PHPAcademy并进行一些免费教程。

这是一个开始:

https://phpacademy.org/videos/php-and-mysql-with-mysqli

如果您希望人们登录您的网站,则必须提供Register & Login教程。

此外,新波士顿还有一些很棒的(免费)教程,你可以查看。

https://www.thenewboston.com/videos.php?cat=87