需求
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);
?>
示例效果