PHP開發(fā)新聞管理系統(tǒng)之修改功能的實(shí)現(xiàn)(下)
上節(jié)我們講到通過在數(shù)據(jù)庫中進(jìn)行查詢,并把代碼展示出來,下面我們來繼續(xù)講解修改的功能,先回顧一下上節(jié)課的完整源碼
<?php header("Content-type: text/html; charset=utf-8");//設(shè)置編碼 $con =@mysql_connect("localhost","root","root") or die("數(shù)據(jù)庫連接失敗"); mysql_select_db('news') or die("指定的數(shù)據(jù)庫不能打開"); mysql_query("set names utf8");//設(shè)置數(shù)據(jù)庫的字符集 $id=$_GET['id']; $sql="select * from new where id=$id"; $res = mysql_query($sql); $row = mysql_fetch_array($res); ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> *{margin:0px;padding:0px;} body{background:#ccc;} .add{width:450px;height:280px;background:#eee;float:left;} .cont{width:500px;height:350px;margin-top:5px;margin-left:5px;} form{margin-left:10px;padding-top:30px;} .sub{width:100px;height:40px;border:1px solid #ccc;} .sub:hover{background:#f90} </style> </head> <body> <div class="add"> <div class="cont"> <form method="post" action="modify.php?id=<?php echo $id;?>"> 標(biāo)題:<input type="text" name="title" value="<?php echo $row['title']?>"></br></br> 內(nèi)容:<textarea cols="50" rows="5" name="content"><?php echo $row['content']?></textarea></br></br> <input type="submit" value="修改" class="sub"> </form> </div> </div> </body> </html>
如上代碼,表單提交到 modify.php 這個(gè)文件 ,接下來我們看一下這個(gè)文件
首先還是要連接數(shù)據(jù)庫
<?php header("Content-type: text/html; charset=utf-8");//設(shè)置編碼 $con =@mysql_connect("localhost","root","root") or die("數(shù)據(jù)庫連接失敗"); mysql_select_db('news') or die("指定的數(shù)據(jù)庫不能打開"); mysql_query("set names utf8");//設(shè)置數(shù)據(jù)庫的字符集
然后獲取表單信息
<?php $id = $_GET['id']; $title = $_POST['title']; $content = $_POST['content']; $messtime = time();
注意:這里我們也需要獲取 id 上一節(jié)課我們是獲取 id 然后在數(shù)據(jù)庫中進(jìn)行查詢,把信息查詢出來,這里我們在修改的過程中是需要條件的,比如修改那條信息,這里我們使用id 將會很方便
接下來寫修改語句
$sql = "update new set title='$title',content='$content',messtime='$messtime' where id='$id'";
$res = mysql_query($sql);
修改語句寫完之后對其進(jìn)行判斷
if($res){
echo "<script>alert('修改成功');location.href='newlist.php';</script>";
}else{
echo "<script>alert('修改失敗');history.go(-1);</script>";
}
完整代碼如下:
<?php header("Content-type: text/html; charset=utf-8");//設(shè)置編碼 $con =@mysql_connect("localhost","root","root") or die("數(shù)據(jù)庫連接失敗"); mysql_select_db('news') or die("指定的數(shù)據(jù)庫不能打開"); mysql_query("set names utf8");//設(shè)置數(shù)據(jù)庫的字符集 $id = $_GET['id']; $title = $_POST['title']; $content = $_POST['content']; $messtime = time(); $sql = "update new set title='$title',content='$content',messtime='$messtime' where id='$id'"; $res = mysql_query($sql); if($res){ echo "<script>alert('修改成功');location.href='newlist.php';</script>"; }else{ echo "<script>alert('修改失敗');history.go(-1);</script>"; } ?>
這樣我們一個(gè)簡單功能的修改就完成了