>  기사  >  백엔드 개발  >  php增删改查,自己写的demo

php增删改查,自己写的demo

PHP中文网
PHP中文网원래의
2017-03-19 09:18:501114검색

  php增删改查,自己写的demo

1.链接数据库通用方法:conn.php


<?php
   //第一步:链接数据库
    $conn=@mysql_connect("localhost:3306","root","root")or die ("mysql链接失败");
  //第二步: 选择指定的数据库,设置字符集
    @mysql_select_db("php_blog",$conn) or die ("db链接失败".mysql_error());
	mysql_query(&#39;SET NAMES UTF8&#39;)or die ("字符集设置错误");

?>


2.增加 add.php


<?php
  include("conn.php");//引入链接数据库
  if(!empty($_POST[&#39;sub&#39;])){
	$title=$_POST[&#39;title&#39;];
	$con=$_POST[&#39;con&#39;];
	echo $sql="insert into news(id,title,dates,contents) value (null,&#39;$title&#39;,now(),&#39;$con&#39;)" ;
	mysql_query($sql);
	echo"插入成功";
  }
?>
<form action="add.php" method="post">
   标题: <input type="text" name="title"><br>
   内容: <textarea rows="5" cols="50" name="con"></textarea><br>
   <input type="submit" name="sub" value="发表">
</form>

3.删除del.php

<?php
  include("conn.php");//引入链接数据库
  if(!empty ($_GET[&#39;id&#39;])){
	 $sql="select * from news where id=&#39;".$_GET[&#39;id&#39;]."&#39;";
	 $query=mysql_query($sql);
	 $rs=mysql_fetch_array($query);
	
  
  }

  if(!empty($_POST[&#39;sub&#39;])){
	$title=$_POST[&#39;title&#39;];
	$con=$_POST[&#39;con&#39;];
	$hid=$_POST[&#39;hid&#39;];
	$sql="update news set title=&#39;$title&#39;,contents=&#39;$con&#39; where id=&#39;$hid&#39; limit 1 ";

	mysql_query($sql);
	echo "<script> alert(&#39;更新成功&#39;); location.href="http://www.php.cn/">
if(!empty($_GET[&#39;del&#39;])){ $d=$_GET[&#39;del&#39;]; $sql="delete from news where id =&#39;$d&#39;"; } $query=mysql_query($sql); echo "删除成功"; ?>

4,改 edit.php页面

<?php
  include("conn.php");//引入链接数据库
  if(!empty ($_GET[&#39;id&#39;])){
	 $sql="select * from news where id=&#39;".$_GET[&#39;id&#39;]."&#39;";
	 $query=mysql_query($sql);
	 $rs=mysql_fetch_array($query);
	
  
  }

  if(!empty($_POST[&#39;sub&#39;])){
	$title=$_POST[&#39;title&#39;];
	$con=$_POST[&#39;con&#39;];
	$hid=$_POST[&#39;hid&#39;];
	$sql="update news set title=&#39;$title&#39;,contents=&#39;$con&#39; where id=&#39;$hid&#39; limit 1 ";

	mysql_query($sql);
	echo "<script> alert(&#39;更新成功&#39;); location.href="http://www.php.cn/">



성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.