標籤:
1.建立資料庫`lyb`
CREATE DATABASE `lyb`;
CREATE TABLE `lyb1` (id INT NOT NULL AUTO_INCREMENT ,title VARCHAR( 200 ) NOT NULL ,content TEXT NOT NULL ,author VARCHAR( 30 )not null DEFAULT ‘彭軍‘,email VARCHAR( 40 ) not null DEFAULT ‘[email protected]‘,PRIMARY KEY ( id ) ,UNIQUE (title)) ENGINE = INNODB DEFAULT CHARSET = utf8
資料庫連接檔案conn.php
header("Content-type: text/html; charset=UTF-8"); $DB_SERVER = "localhost"; $DB_NAME = "root"; $DB_PWD = ""; $conn = mysql_connect($DB_SERVER,$DB_NAME,$DB_PWD); if (!$conn) { die("串連資料庫失敗".mysql_errno()); } mysql_query("set names utf8");
2.建立前台頁面 5.1.php
<?php/* * * @Authors peng--jun * @Email [email protected] * @Date 2015-11-07 13:50:48 * @Link http://www.cnblogs.com/xs-yqz/ * @version $Id$ ========================================== */ header("Content-type: text/html; charset=UTF-8"); if (isset($_POST[‘submit‘])) { require("include/conn.php"); mysql_select_db("lyb",$conn);//選擇資料庫 $title = $_POST[‘title‘]; $author = $_POST[‘author‘]; $content = $_POST[‘content‘]; $email = $_POST[‘email‘]; $result = mysql_query("insert into `lyb1`(`id`,`title`,`content`,`author`,`email`) values(null,‘$title‘,‘$content‘,‘$author‘,‘$email‘)"); var_dump($result); mysql_free_result($result); mysql_close($result);}?><!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>添加資料頁面</title></head><body> <form action="5.1.php" method="POST"> <p>添加新聞頁面</p> <div>標題:<input type="text" name="title" id=""></div> <div>內容: <textarea name="content" id="" cols="30" rows="5"></textarea></div> <div>作者:<input type="text" name="author" id=""></div> <div>郵箱:<input type="text" name="email" id=""></div> <div><input type="reset" value="重設"><input type="submit" name="submit" value="提交"></div> </form></body></html>
3.從資料庫中擷取資料顯示在前台頁面
<?php/* * * @Authors peng--jun * @Email [email protected] * @Date 2015-11-07 13:40:08 * @Link http://www.cnblogs.com/xs-yqz/ * @version $Id$ ========================================== */ header("Content-type: text/html; charset=UTF-8"); require("include/conn.php"); mysql_select_db("lyb",$conn);//選擇資料庫 $result = mysql_query("select * from `lyb1`",$conn);//選擇資料庫表 ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>新聞顯示頁面</title> </head> <body> <table border="1"> <tr bgcolor="#ccc"> <th>序號</th> <th>標題</th> <th>內容</th> <th>作者</th> <th>郵箱</th> </tr> <?php while ($row = mysql_fetch_assoc($result)) { ?> <tr> <td><?= $row[‘id‘]?></td> <td><?= $row[‘title‘]?></td> <td><?= $row[‘content‘]?></td> <td><?= $row[‘author‘]?></td> <td><?= $row[‘email‘]?></td> </tr> <?php } ?> </table> <p>共有<?= mysql_num_rows($result) ?>條記錄 </p> <!-- mysql_num_rows()函數返回的是結果集的總數 --> <?php //釋放資源,關閉結果集 mysql_free_result($result); mysql_close($result); ?> </body> </html>
頁面瀏覽
php訪問資料庫