为了账号安全,请及时绑定邮箱和手机立即绑定

请问一下create方法报错这是怎么回事

  
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

正在回答

3 回答

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
   ];
}

0 回复 有任何疑惑可以回复我~

贴代码朋友,不贴大家都只能猜,最好带上请求参数

0 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消

请问一下create方法报错这是怎么回事

我要回答 关注问题
意见反馈 帮助中心 APP下载
官方微信