php完成mysql增删改功能
笔者通过表单POST方法,将前端的数据传到后端进行数据库增删改操作,核心就是后端处理的php文件要取得$_POST["字段"]的值。
1、insert
<?php
include "conn.php";
header("Content-Type: text/html; charset=utf-8");
$time = $_POST["time"];
$volume = $_POST["volume"];
$AD = $_POST["AD"];
// $remark = $_POST["remark"];
//数据表有AUTO_INCREMENT的主键时,需要字段对应好,否则出错
$sqlstr = "insert into records(TIME,VOLUME,AD) values('$time','$volume','$AD')";
$result=mysqli_query($conn, $sqlstr);
if ($result) {
#echo "新记录插入成功 ".date("h:i:sa");
#echo "<script>alert('新纪录添加成功');window.location.href='add.php';</script>";
// echo "<script>alert('新纪录添加成功');location='index.php';</script>";
echo "<script>location='YIYI.php#templatemo_timeline';</script>";
//echo "新纪录添加成功。".date("h:i:sa");
} else {
echo "Error: " . $sqlstr . "<br>" . mysqli_error($conn);
}
//一条记录不需清除,出错
//mysqli_free_result($result);
mysqli_close($conn);
?>
2、delete
<?php
include "conn.php";
header("Content-Type: text/html; charset=utf-8");
$ID = $_POST["ID"];
//数据表有AUTO_INCREMENT的主键id
$sqlstr ="delete from records where id=$ID";
$result=mysqli_query($conn, $sqlstr);
if ($result) {
//echo "删除成功 ".date("h:i:sa");
echo "<script>location='YIYI.php#templatemo_timeline';</script>";//定位新文档
#echo "<script>alert('纪录删除成功');history.go(-1);</script>";
// echo "<script>alert('纪录删除成功');window.location.href='index_mysql_model.php';</script>";
} else {
echo "Error: " . $sqlstr . "<br>" . mysqli_error($conn);
}
//一条记录不需清除,出错
//mysqli_free_result($result);
mysqli_close($conn);
?>
3、update
<?php
include "conn.php";
header("Content-Type: text/html; charset=utf-8");
$id=$_POST["id"];
$time=$_POST["time"];
$volume = $_POST["volume"];
$AD = $_POST["AD"];
//数据表有AUTO_INCREMENT的主键时,需要字段对应好,否则出错
//$sqlstr ="insert into websites(name,url,alexa,country) values('$name','$url','$alexa','$country')";
$sqlstr="update records set TIME='$time', VOLUME='$volume',AD='$AD' where ID=$id";
$result=mysqli_query($conn, $sqlstr);
if ($result) {
//echo "记录修改成功 ".date("h:i:sa");
#echo "<script>alert('新纪录添加成功');window.location.href='add.php';</script>";
// echo "<script>alert('纪录更新成功');history.go(-1);</script>";
echo "<script>location='YIYI.php#templatemo_timeline';</script>";//定位新文档
} else {
echo "Error: " . $sqlstr . "<br>" . mysqli_error($conn);
}
//一条记录不需清除,出错
//mysqli_free_result($result);
mysqli_close($conn);
?>