19951204
2017-11-06 17:35
Fatal error: Uncaught exception 'Exception' with message '发布文章失败' in C:\phpStudy\PHPTutorial\WWW\article\lib\Article.php:47 Stack trace: #0 C:\phpStudy\PHPTutorial\WWW\article\index.php(15): Article->create('\xE6\x96\x87\xE7\xAB\xA0\xE6\xA0\x87\xE9\xA2\x981', '\xE6\x96\x87\xE7\xAB\xA0\xE5\x86\x85\xE5\xAE\xB91', 1) #1 {main} thrown in C:\phpStudy\PHPTutorial\WWW\article\lib\Article.php on line 47
index.php
require __DIR__.'/lib/Article.php';
$pdo=new PDO('mysql:host=localhost;dbname=res','root','root');
$article = new article($pdo);
var_dump($article->create('文章标题1','文章内容1',1))
Article.php
require_once __DIR__."/ErrorCode.php";
class Article{
private $_db;
public function __construct($_db){
$this->_db = $_db;
}
public function create($title,$content,$userId){
if(empty($title)){
throw new Exception("文章标题不能为空", ErrorCode::ARTICLE_TITLE_CANNOT_EMPTY);
}
if(empty($content)){
throw new Exception("文章内容不能为空", ErrorCode::ARTICLE_CONTENT_CANNOT_EMPTY);
}
$addtime = time();
//数据写入
$sql = 'INSERT INTO `article` (`title`,`content`,`addtime`,`user_id`) VALUES(:title,:content,:addtime,:user_id)';
$stmt = $this->_db->prepare($sql);
$stmt->bindParam(':title',$title);
$stmt->bindparam(':content',$content);
$stmt->bindparam(':addtime',$addtime);
$stmt->bindparam(':user_id',$userId);
if(!$stmt->execute()){
throw new Exception("发布文章失败", ErrorCode::ARTICLE_CREATE_FAIL);
}
return [
'articleId' => $this->_db->lastInsertId(),
'title' => $title,
'content' => $content,
'addtime' => $addtime,
'userId' => $userId
];
}
贴代码朋友,不贴大家都只能猜,最好带上请求参数
Restful API实战
44002 学习 · 118 问题
相似问题