需求
- PHP連接數據庫
- POST傳參更新數據
- 查詢更新后的數據
PHP連接數據庫
//config.php文件內容
$database = "xx";
$dataname = "root";
$datapasswd = "xxx";
$datalocal = "localhost:3306";
//$dataport = "3306";
$con = mysqli_connect($datalocal,$dataname,$datapasswd,$database);
if(!$con){
echo "數據庫連接異常";
}
//設置查詢數據庫編碼
mysqli_query($con,'set names utf8');
HTML表單
<html>
<center>
<p>需要修改的用戶名和密碼</p>
<form action="update.php" method="post">
id: <input type="text" name="id">
用戶名: <input type="text" name="name">
密碼: <input type="text" name="password">
<input type="submit" value="提交">
</form>
</center>
</html>
POST傳參更新數據
<?php
//接收參數
$id = $_POST['id'];
$name = $_POST['name'];
$password = $_POST['password'];
//update更新需要條件
//UPDATE table_name SET field1=new-value1, field2=new-value2
$sql = "UPDATE user set name='$name',password='$password' where id=$id";
$result = mysqli_query($con,$sql);
if(!$result){
echo "更新失敗</br>";
}
else{
echo "</hr><center>成功更新數據</center></br>";
}
查詢更新后的數據
$query = "select * from user";
$result1 = mysqli_query($con,$query);
//函數返回結果集中行的數量
if(mysqli_num_rows($result1)>0){
//mysqli_fetch_array以數組的形式返回,關聯數組
while($row = mysqli_fetch_array($result1)){
echo
"<center>
<table>
<tr>
<th>賬號</th>
<th>密碼</th>
</tr>
<tr>
<td>".$row['id']."</td>
<td>".$row['name']."</td>
<td>".$row['password']. "</td>
</tr>
</table>
</center>";
}
}
//關閉數據庫
mysqli_close($con);
