1,连接数据库
try{
// mysql数据类行;dbname=数据库;post:端口号;charset=utf8:设置字符集;用户名;密码
$conn=new PDO("mysql:host=localhost;dbname=mycalss;port=3306;charset=utf8",'root','root');
}catch(PDOException $e){
echo "输出异常".$e->getMessage();
}
//设置的function.php文件方便重复用到
修改
<?php
//连接数据库
require "function.php";
//执行SQLy语句(修改语句);
$sql="update my_student set stu_name=:name,sex=:sex,age=:age,birthday=:birthday where studentid=:id ";
//预处理
$stmt=$conn->prepare($sql);
$name=$_POST['name'];
$age=$_POST['age'];
$sex=$_POST['sex'];
$birthday=$_POST['birthday'];
$id=$_POST['id'];
//绑定参数:array(":name"=>$name,":sex"=>$sex,":age"=>$age,":birthday"=>$birthday,":id"=>$id)
//$stmt-bindParam(':name',$name);
//执行(返回true或者false)
$flag=$stmt->execute(array(":name"=>$name,":sex"=>$sex,":age"=>$age,":birthday"=>$birthday,":id"=>$id));
if($flag==true){
echo "<script>
alert('修改成功!');
location.href='index.php';
</script>";
}else{
echo "<script>
alert('出了一点问题,请重新修改');
location.href='index.php';
</script>";
}
**
删除*
<?php
//也是连接数据库
require 'function.php';
//变量$id值通过GET方法取得传递过来的id值
$id=$_GET['id'];
//执行SQLy语句(删除语句);
$sql="delete from my_student where studentid=:id";
//预处理
$stmt=$conn->prepare($sql);
//执行(返回true或者false)
$flag=$stmt->execute(array(":id"=>$id));
if ($flag==true){
echo "<script>
alert('删除成功');
location.href='index.php';
</script>";
}else{
echo "<script>
alert('删除失败');
location.href='index.php';
</script>";
}
添加
<?php
//连接数据库
require "function.php";
//执行SQL语句(添加语句)
$sql="insert into my_student(stu_name,sex,age,birthday) values(:name,:sex,:age,:birthday)";
//预处理
$stmt =$conn->prepare($sql);
$name=$_POST['stu_name'];
$age=$_POST['age'];
$sex=$_POST['sex'];
$birthday=$_POST['birthday'];
//执行
$flag=$stmt->execute(array(":name"=>$name,":sex"=>$sex,":age"=>$age,":birthday"=>$birthday));
if ($flag){
echo "<script>
alert('添加成功');
location.href='index.php';
</script>";
}else{
echo "<script>
alert('添加失败');
location.href='index.php';
</script>";
}
查询
<?php
//连接数据库
require "function.php";
//执行SQL语句
$sql="select * from my_student age between :min and :max";
//预处理
$stmt=$conn->perpare($sql);
$min=10;
$max=20;
//绑定参数
/*第一种
$stmt->bindParam(":min",$min)
$stmt->bindParam(":max",$max)
$flag=$stm->execute
*/
//第二种
$flag=$stmt->execute(array(":min"=>$min,":max"=>$max));
if($flag){
//得到结果集
$result=$stmt->fetchAll(PDO::FETCH_ASSOC);
//对结果及进行处理
echo "<table border='1'><tr><th>姓名</th><th>性别</th><th>年龄</th></tr>";
foreach($result as $row){
echo "<tr><td>$row[name]</td><td>$row[sex]</td><td>$row[age]</td></tr>";
echo "</table>";
}
}else{
echo "失败";
}