Add function (2)
Let’s take a look at the php code to add functions.
Adding data must be added to the database, so the first step must be to connect to the database first.
<?php $link = mysqli_connect("localhost","root","root","joke"); if (!$link) { die("连接失败: " . mysqli_connect_error()); } ?>
We may also need to use the code to connect to the database later, so we can Extract this code and put it in a separate file. In the future, you can directly reference the file, such as naming it config.php. In the future, we only need to include and reference it.
The next step is to receive the value passed by the front-end form page. It is the same as the previous registration.
The other thing about image uploading is to implement it by instantiating the calling class method. Of course you can also write it yourself.
<?php if($_POST){ date_default_timezone_set("PRC"); //设置时区 $author = isset($_POST['author'])?$_POST['author']:""; //获取表单传递过来的值 $content = isset($_POST['content'])?$_POST['content']:""; $cid = isset($_POST['cid'])?$_POST['cid']:""; require 'fileupload.class.php'; //引用类文件 $upobj=new FileUpload(); //实例化调用类 $ret=$upobj->upload('pic'); if($ret==1){ $creat_time = date("Y-m-d H:i:s"); ?>
The function date_default_timezone_set() sets the time zone, and "PRC" represents the Chinese time zone.
When using the reference class method, you need to know something about the class file, otherwise reference errors may occur.
The next step is to insert the received data into the database, use the insert into statement
<?php if($author && $content && $creat_time && $cid){ $sql ="insert into list(author,content,creat_time,image,cid) values('$author','$content','$creat_time','{$upobj->newpath}',$cid)"; $rel = mysqli_query($link,$sql); if($rel) { echo "添加成功" . "<br/><br/>"; echo "<a href='list.php'>跳转至列表页面</a>"; } }else { echo "添加失败" . "<br/><br/>"; echo "<a href='add.php'>跳转至添加页面</a>"; } } ?>
First write the insert statement, then execute the insert statement, assign the return value to the variable $rel, and determine whether $rel is If there is no value, the addition will be successful. If not, the addition will fail.
Finally, our added function is complete.