php 创建表单和连接数据库
创建一个表单
html文件add
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="add.php" method="post">
学号:<input type="text" name="number"><br>
姓名:<input type="text" name="name"><br>
年龄:<input type="text" name="age"><br>
性别:<input type="radio" name="sex" value="男">男
<input type="radio" name="sex" value="女">女<br>
<input type="submit">
</form>
</body>
</html>
赋值插入数据库
php文件add
<?php
try{
$db = new PDO("mysql:host=127.0.0.1;dbname=school", 'root', 'root');
}catch(PDOException $e) {
print"error";
}
$number = $_POST['number'];
$name = $_POST['name'];
$age = $_POST['age'];
$sex=$_POST['sex'];
$q=$db->query("select * from s_student where 学号=$number");
$row=$q->fetch();
if (!"$row[学号]"){
$sql = "insert into s_student values(?,?,?,?)";
header("location:list.php");
$stmt = $db->prepare($sql);
$stmt->bindValue(1,"$number");
$stmt->bindValue(2,"$name");
$stmt->bindValue(3,"$age");
$stmt->bindValue(4,"$sex");
$stmt->execute();
}
else {
echo"该学生已存在于列表中,请勿重复添加!";
}
list在网页显示表单,跳转删除
<?php
try {
$db = new PDO("mysql:host=127.0.0.1;dbname=school", 'root', 'root');
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<table border="1">
<tr>
<th>学号</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>删除</th>
</tr>
<?php
$q=$db->query("select * from s_student");
while($row=$q->fetch()) {
?>
<tr>
<td><?php
echo "$row[学号]";
?></td>
<td><?php
echo "$row[姓名]";
?></td>
<td><?php
echo "$row[年龄]";
?></td>
<td><?php
echo "$row[性别]";
?></td>
<td><a href="delete.php?学号=<?php
echo "$row[学号]";
?>">删除</a>
</td>
</tr>
<?php
}
?>
</table>
</body>
</html>
删除功能
<?php
try {
$db = new PDO("mysql:host=127.0.0.1;dbname=school", 'root', 'root');
} catch (PDOException $e) {
echo $e->getMessage();
}
$number= $_GET['学号'];
echo "$number 1";
$Sql = "delete from s_student where 学号=?";
$stmt = $db->prepare($Sql);
$stmt->bindValue(1, "$number");
$stmt->execute();
$affect_row = $stmt->rowCount();
if ($affect_row) {
echo '删除成功' . '<br>';
header("location:list.php");
} else {
echo '删除失败' . '<br>';
}
$stmt = null;
$pdo = null;
```**