参考视频:https://www.bilibili.com/video/BV1Js411i74j?p=8
环境:phpstudy 2018 PHP 5.X PHPmyadmin
目录结构 :
运行效果:
代码: 第一个文件,文件名为 item.php
<?php
class Message{
var $name;
var $time;
var $contet;
function __construct($n,$t,$c){
$this->name = $n;
$this->time = $t;
$this->content = $c;
}
function show(){
echo "Name :".$this->name."<br>";
echo "Time :".$this->time."<br>";
echo "Content :".$this->content."<br>";
echo "=================================================="."<br>";
}
}
//$m = new Message ("zhang","2020-3-6","xxxxxxxx");
//$m->show();
class DB{
var $database = null ;
function __construct (){
$dbhost = "localhost";
$account = "root";
$password = "root";
$this->database = mysql_connect($dbhost,$account,$password); //连接phpmyadmin
if($this->database){
echo "connection ";
}else{
echo "fail ";
}
$result = mysql_select_db("db_message2",$this->database); //连接成功之后,继续选择连接phpmyadmin中的具体哪个数据库
if($result){
echo "choose ";
}else{
echo "fail choose !!";
}
}
}
$a = new DB();
?>
第二个文件 文件名为 MessageBoard.php 代码如下
<?php
include_once (‘item.php‘);
class MessageBoard extends DB{ //extends 是继承父类的数据库
var $messages = array();
function __construct(){
parent::__construct(); //写这个的原因是,因为这里已经有了一个__construct了,还需要在导入上面那个__construct,所以说得声明一下
$this->receivemessage();
$this->loaddata();
$this->showallmessage();
$this->showform();
}
function receivemessage(){
echo "1";
if(count($_POST) != 0){
//$this->savedata($_POST[‘username‘],data("Y-m-d h:i:s",time()),$_POST[‘content‘]);
$this->savedata($_POST[‘username‘],$_POST[‘time‘],$_POST[‘content‘]);
}
}
function savedata($u,$t,$c){
/*echo "username :".$u."<br>";
echo "time :".$t."<br>";
echo "content :".$c."<br>";*/
echo ‘<br>‘.$_POST[‘username‘];
$sql = "INSERT INTO `db_message2`.`all_messages2` (`id`, `name`, `time`, `content`) VALUES (NULL, ‘".$u."‘, ‘".$t."‘, ‘".$c."‘);";
mysql_query($sql);
echo ‘fffffffffffff‘;
echo "2";
}
function loaddata(){
echo "3";
//$temp = new Message("zhang","2013-9-6","hahhahahaha");
$sql = "SELECT * FROM `all_messages2` LIMIT 0, 30 ";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)){ //这些都是最后在完善的,先写大的框架,也就是先写函数,最后在完善函数
$temp = new Message( $row[‘name‘], $row[‘time‘],$row[‘content‘]);
array_push($this->messages , $temp);
}
}
function showallmessage(){
echo "4";
foreach($this->messages as $m ){ //这些都是最后在完善的,先写大的框架,也就是先写函数,最后在完善函数
$m->show();
}
}
function showform(){
echo "5";
echo "<form action=‘‘ method=‘POST‘>";
echo "Name: "."<input type=‘text‘ name=‘username‘>"."<br>";
echo "time: "."<input type=‘text‘ name=‘time‘>"; //这些都是最后在完善的,先写大的框架,也就是先写函数,最后在完善函数
echo "Content: "."<input type=‘text‘ name=‘content‘>";
echo "<input type=‘submit‘>";
echo "</form>";
}
}
$mb = new MessageBoard();
?>
数据库结构
总结和记录常犯的几个错误:
1.可能C和PY的代码写习惯了,变量名前面老是忘记加$符号。
2.不要看PHP留言板这个项目很小,越小的项目,越能看出一个人的功底。这个项目虽然说很小,但是在写项目之前也要把思路捋清楚,最好是画个E-R图,不要怕浪费时间,一个项目真正浪费时间的并不是写代码的时候,而是写代码的思考,把E-R图写出来,照着E-R图写,不就清楚多了,养成好习惯,做大项目会受益的。
3.写代码的时候不要一个功能一个功能的写,先把整体的框架写出来,在慢慢完善每个功能!!!!
4.不得不说,PHP写后台确实容易些,归根结底就是发展时间久,函数啥的都很全面。