PHP实现 Discuz站外发帖类(直连操作数据库)
这里借鉴了另一个帖子 区块链攻城狮
因业务需求,需要做一个完全独立的站外发帖API
主要操作了Discuz数据表如下:
- pre_forum_thread - 主题表
- pre_forum_post_tableid - post 分表协调表
- pre_forum_post - 帖子表
- pre_forum_forum - 版块表
- pre_common_member_count - 用户统计表
封装成了类,直接用就行了,自行修改构造函数里的数据库信息
该方法适用于DiscuzX3.4,其他版本需自行测试.(测试前请备份数据库)
代码如下:
<?php
$test=new insert_content('1','admin');
// 参数1=板块id
// 参数2=帖子标题
// 参数3=帖子内容
var_dump($test->insert_post(56,"站外发帖标题","帖子内容"));
class insert_content{
/**
* @var _prefix=数据表前缀
*/
private $_prefix='pre'; //这里修改Discuz的数据表前缀
private $_con;
private $_sql;
private $_tid;
private $_fid;
private $_pid;
private $_authorid;
private $_author;
private $_time;
private $_title;
private $_content;
public function __construct($authorid,$_author){
$this->_authorid=$authorid;
$this->_author=$_author;
$this->_time=time();
// 初始化对象时连接数据库
$this->_con=mysqli_connect('host','user','pass','sqldb',3306);
}
public function insert_post($fid,$title,$content){
$this->_fid=$fid;
$this->_title=$title;
$this->_content=$content;
// 第一步:向 主题表 pre_forum_thread 中插入版块ID、用户ID、用户名、帖子标题、发帖时间等信息。
$this->_sql="INSERT INTO {$this->_prefix}_forum_thread SET fid='{$this->_fid}',authorid='{$this->_authorid}',author='{$this->_author}',subject='{$this->_title}',dateline='{$this->_time}',lastpost='{$this->_time}',lastposter='{$this->_author}'";
mysqli_query($this->_con,$this->_sql);
// 第二步:获取第一步插入表 pre_forum_thread 的数据ID,作为主题ID,即 tid
$this->_tid=mysqli_query($this->_con,"SELECT LAST_INSERT_ID()")->fetch_assoc()['LAST_INSERT_ID()'];
// 第三步:向 post 分表协调表 pre_forum_post_tableid 插入一条数据,这张表中只有一个自增字段 pid
mysqli_query($this->_con,"INSERT INTO {$this->_prefix}_forum_post_tableid SET pid=''");
// 第四步:获取 第三步 插入表 pre_forum_post_tableid 的数据ID,作为 pid
$this->_pid=mysqli_query($this->_con,"SELECT LAST_INSERT_ID()")->fetch_assoc()['LAST_INSERT_ID()'];
// 第五部:向帖子表 pre_forum_post 中插入帖子相关信息,这里需要注意的是: pid为第四部的pid值,tid为第二步的tid值
$this->_sql="INSERT INTO {$this->_prefix}_forum_post SET pid='{$this->_pid}', fid='{$this->_fid}', tid='{$this->_tid}', author='{$this->_author}', authorid='{$this->_authorid}', subject='{$this->_title}', dateline='{$this->_time}', message='{$this->_content}'";
mysqli_query($this->_con,$this->_sql);
// 第六部:更新版块 pre_forum_forum 相关主题、帖子数量信息
$this->_sql="UPDATE {$this->_prefix}_forum_forum SET posts=posts+1,threads=threads+1 WHERE fid='{$this->_fid}'";
mysqli_query($this->_con,$this->_sql);
// 第七步:更新用户 pre_common_member_count 帖子数量信息
$this->_sql="UPDATE {$this->_prefix}_common_member_count SET posts=posts+1,threads=threads+1 WHERE uid='{$this->_authorid}'";
mysqli_query($this->_con,$this->_sql);
return $this->_tid;
}
public function __destruct(){
// 调用结束断开数据库连接
$this->_con->close();
}
}
效果图:
返回tid表示已经成功发帖
该方法不安全不安全不安全,重要的事情说三遍.
只是贪图方便,接入时需要自行做好安全措施
还需修改其他字段可以自行发挥想象
有什么问题可以私信我