数据的删除应用delete语句,而在PHP中需要通过mysql_query()函数来执行delete删除语句,完成MySQL数据库中数据的删除操作。
例下面删除新闻信息表中的新闻信息。
具体步骤如下:
(1)创建数据库连接文件conn.php,代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<?php
$conn=mysql_connect("localhost","root","111"); //连接数据库服务器
mysql_select_db("db_database08",$conn); //连接db_database08数据库
mysql_query("set names utf8"); //设置数据库编码格式
?>
</body>
</html>
(2)创建index.php文件,显示所有新闻信息,代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
* { margin:0; padding:0; }
body { font-family:Verdana, Arial, Helvetica, sans-serif; font-size:16px; width:1010px; margin:0 auto; }
p { line-height:220%; }
#layout {background:#cccccc;font-size:18px; }
#layout { text-indent:2em; letter-spacing:0.5px; }
#edit { background:#0000FF; }
#edit p {text-indent:2px; letter-spacing:1px;}
</style>
</head>
<body>
<form id="form1" name="form1" method="post" action="index_ok.php">
<?php
include("conn.php"); //包含conn.php文件
$arr=mysql_query("select * from tb_news",$conn); //查询数据
/*使用while语句循环mysql_fetch_array()函数返回的数组*/
while($result=mysql_fetch_array($arr)){
?>
<p><?php echo $result['name'];?></p> <!--输出新闻标题-->
<div id="layout">
<p><?php echo $result['news'];?></p> <!--输出新闻内容-->
</div>
<p><input type="hidden" name="id" value="<?php echo $result['id'];?>" /></p>
<div id="edit">
<p><input name="Submit" type="Submit" value="删除" /></p>
</div>
<?php
} //结束while循环
?>
</form>
</body>
</html>
(3)创建index_ok.php文件,显示要编辑的新闻内容,代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<?php
include("conn.php"); //包含conn.php文件
if(isset($_POST['id']) and isset($_POST['Submit']) and $_POST['Submit']=="删除"){
$delete=mysql_query("delete from tb_news where id='".$_POST['id']."'",$conn);
if($delete){
echo "<script> alert('删除成功!'); window.location.href='index.php'</script>";
}else{
echo "<script> alert('删除失败!'); window.location.href='index.php'</script>";
}
}
?>
</body>
</html>