需求
1. 使用PHP連接數據庫
2. 使用POST方法傳參添加數據進入數據庫
3. 使用PHP添加數據到數據庫中
4. 顯示成功插入的數據記錄
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');
實例代碼
<?php
header ( "Content-type:text/html;charset=utf-8" );
include './inc/config.php';
//通過表單插入數據到數據庫中
?>
<html>
<center>
<form action="insert.php" method="post">
名字: <input type="text" name="name">
密碼: <input type="text" name="password">
ling: <input type="text" name="con">
<input type="submit" value="提交">
</form>
</center>
</html>
<?php
//接收參數
$name = $_POST['name'];
$password = $_POST['password'];
$ling = $_POST['con'];
// //插入數據庫
$sql = "insert into user (name,password,con) value ('$name','$password','$ling')";
$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['name']."</td>
<td>".$row['password']. "</td>
</tr>
</table>
</center>";
}
}
//關閉數據庫
mysqli_close($con);
?>
示例效果
