public function createPost($data) { $currentUser = parent::authenticateUser(); $post = new Post(); if (isset($data->title) && isset($data->content)) { $post->setTitle($data->title); $post->setContent($data->content); $post->setAuthor($currentUser); } try { // validate Post object $post->checkIsValidForCreate(); // if it fails, ValidationException // save the Post object into the database $postId = $this->postMapper->save($post); // response OK. Also send post in content header($_SERVER['SERVER_PROTOCOL'] . ' 201 Created'); header('Location: ' . $_SERVER['REQUEST_URI'] . "/" . $postId); header('Content-Type: application/json'); echo json_encode(array("id" => $postId, "title" => $post->getTitle(), "content" => $post->getContent())); } catch (ValidationException $e) { header($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad request'); echo json_encode($e->getErrors()); } }
public function create($content, $idAuthor, Topic $Topic, SCategory $SCategory) { $post = new Post($this->db); try { $post->setContent($content); $post->setIdAuthor($idAuthor); $post->setTopic($Topic); $post->setSCategory($SCategory); } catch (Exception $e) { $errors = $e->getMessage(); echo $errors; } if (!isset($err)) { $content = $this->db->quote($post->getContent()); $idAuthor = $post->getIdAuthor(); $idTopic = $post->getIdTopic(); $idSCategory = $post->getIdSCategory(); $query = 'INSERT INTO post(content, id_author, id_topic, id_sCategory) VALUE (' . $content . ',' . $idAuthor . ', ' . $idTopic . ', ' . $idSCategory . ')'; } $res = $this->db->exec($query); if ($res) { $id = $this->db->lastInsertId(); if ($id) { return $this->findById($id); } else { throw new Exception('Database error'); } } else { throw new Exception($errors); } }
function addPost($post) { if (isset($this->content) && is_array($this->content)) { $this->content[] = $post; } else { parent::setContent(array($post)); } $this->update(); return $this; }
private function processResults($statement) { $results = array(); if ($statement) { while ($row = $statement->fetch(PDO::FETCH_OBJ)) { $post = new Post(); $post->setId($row->post_id); $post->setTitle($row->title); $post->setContent($row->content); $results[] = $post; } } return $results; }
/** * Console-only route to generate fixtures. */ public function fixturesAction() { $em = $this->getEntityManager(); for ($i = 0; $i < 100; $i++) { $post = new Post(); $post->setTitle('Post ' . uniqid()); $post->setIntro(str_repeat('intro ', rand(1, 100))); $content = ''; for ($j = mt_rand(1, 100); $j > 0; $j--) { $content .= str_repeat('lorem ipsum ', rand(1, 20)); } $post->setContent($content); $em->persist($post); } $em->flush(); }
/** * savePost saves / creates a post * * @param Slim_Http_Request $request * @param \stojg\puny\Post $post */ public static function save_post(\Slim_Http_Request $request, Post $post) { $post->setContent($request->post('content'))->setTitle($request->post('title'))->setDate($request->post('date'))->setCategories($request->post('categories'))->setDraft($request->post('draft'))->save('posts'); }
public function create($idTopic, $content) { $post = new Post(); $set = $post->setContent($content); if ($set === true) { $manager = new TopicManager($this->db); $topic = $manager->findById($idTopic); $set = $post->setIdTopic($topic); if ($set === true) { if (isset($_SESSION['id'])) { $manager = new UserManager($this->db); $user = $manager->getCurrent(); $set = $post->setIdAuthor($user); if ($set === true) { $idAuthor = intval($user->getId()); $idTopic = intval($post->getIdTopic()); $content = mysqli_real_escape_string($this->db, $post->getContent()); $query = "INSERT INTO post (id_author, id_topic, content) VALUES (" . $idAuthor . ", " . $idTopic . ", '" . $content . "')"; $result = mysqli_query($this->db, $query); if ($result) { $id = mysqli_insert_id($this->db); if ($id) { return $this->findById($id); } else { return "Erreur serveur."; } } else { return mysqli_error(); } } else { return $set; } } else { return "Utilisateur déconnecté."; } } else { return $set; } } else { return $set; } }
$db = mysql_connect(WALKER_DB_HOST, WALKER_DB_USERNAME, WALKER_DB_PASSWORD) or die('Could not connect: ' . mysql_error()); mysql_select_db(WALKER_DB_NAME); mysql_query('SET NAMES utf8'); mysql_query('SET CHARACTER SET utf8'); mysql_query("SET COLLATION_CONNECTION='utf8_general_ci'"); if (isset($_POST['method'])) { $post = new Post(); switch ($_POST['method']) { case 'new': check_login(); $post->setTitle($_POST['title']); $post->setAuthor($_SESSION['user']); $post->setTags($_POST['tags']); $post->setReply($_POST['reply']); $post->setShow($_POST['show']); $post->setContent($_POST['content']); $id = $post->newTopic(); mysql_close($db); echo 'ok'; //header("Location: http://www.n7money.cn/view/$id.html"); break; case 'modify': check_login(); $post->setId(intval($_POST['topic_id'])); $post->setTitle($_POST['title']); $post->setCreated($_POST['created']); $post->setAuthor($_SESSION['user']); $post->setReply($_POST['reply']); $post->setShow($_POST['show']); $post->setContent($_POST['content']); $post->setTags($_POST['tags']);
/** * * @param sfWebRequest $request * @param sfForm $form * @param Room $room * @return <bool> false if preview action */ protected function processTopicForm(sfWebRequest $request, sfForm $form, Room $room, User $user) { $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName())); if ($form->isValid()) { if ($this->getRequestParameter('submitAct')) { $values = $form->getValues(); // topic saving $topic = new Topic(); $topic->setTitle($values['title']); $topic->setIdRoom($room->getId()); $topic->setIdUser($user->getId()); $topic->save(); // post saving $post = new Post(); $post->setContent($values['post']['content']); $post->setIdTopic($topic->getId()); $post->setIdUser($user->getId()); $post->save(); $this->redirect('room_topic_show', $topic); } else { if ($this->getRequestParameter('prevSubmitAct')) { return; } else { return false; } } } }
<?php include_once 'Registry.php'; include_once 'dao/PostDAO.php'; include_once 'model/Post.php'; // Instanciar uma conexão com PDO $conn = new PDO('mysql:host=localhost;port=3306;dbname=example-pdo', 'user', 'password'); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Armazenar essa instância no Registry $registry = Registry::getInstance(); $registry->set('Connection', $conn); // Instanciar um novo Post e setar informações $primeiroPost = new Post(); $primeiroPost->setTitle('Primeiro post'); $primeiroPost->setContent('Conteudo!'); // Instanciar um novo Post e setar informações $segundoPost = new Post(); $segundoPost->setTitle('Segundo post'); $segundoPost->setContent('Conteudo!'); // Instanciar o DAO e trabalhar com os métodos $postDAO = new PostDAO(); $postDAO->insert($primeiroPost); $postDAO->insert($segundoPost); // Resgatar todos os registros e iterar $results = $postDAO->getAll(); foreach ($results as $post) { echo $post->getTitle() . '<br />'; echo $post->getContent() . '<br />'; echo '<br />'; }
/** * Makes a new post by this user * * @param int $threadID * @param string $postBody * @return bool */ public function makeNewPost($threadID, $postBody) { //If the user is banned, they can't make a new post if ($this->getHidden()) { return false; } //Create the post $post = new Post(); $post->setThreadId($threadID); $post->setContent($postBody, sfConfig::get('app_general_allowed_html_tags')); $post->setPosterId($this->getId()); //If the post wasn't correctly added to the DB, return false return $post->save(); }
/** * Action to add a new post * * When called via GET, it shows the add form * When called via POST, it adds the post to the * database * * The expected HTTP parameters are: * <ul> * <li>title: Title of the post (via HTTP POST)</li> * <li>content: Content of the post (via HTTP POST)</li> * </ul> * * The views are: * <ul> * <li>posts/add: If this action is reached via HTTP GET (via include)</li> * <li>posts/index: If post was successfully added (via redirect)</li> * <li>posts/add: If validation fails (via include). Includes these view variables:</li> * <ul> * <li>post: The current Post instance, empty or * being added (but not validated)</li> * <li>errors: Array including per-field validation errors</li> * </ul> * </ul> * @throws Exception if no user is in session * @return void */ public function add() { if (!isset($this->currentUser)) { throw new Exception("Not in session. Adding posts requires login"); } $post = new Post(); if (isset($_POST["submit"])) { // reaching via HTTP Post... // populate the Post object with data form the form $post->setTitle($_POST["title"]); $post->setContent($_POST["content"]); // The user of the Post is the currentUser (user in session) $post->setAuthor($this->currentUser); try { // validate Post object $post->checkIsValidForCreate(); // if it fails, ValidationException // save the Post object into the database $this->postMapper->save($post); // POST-REDIRECT-GET // Everything OK, we will redirect the user to the list of posts // We want to see a message after redirection, so we establish // a "flash" message (which is simply a Session variable) to be // get in the view after redirection. $this->view->setFlash("Post \"" . $post->getTitle() . "\" successfully added."); // perform the redirection. More or less: // header("Location: index.php?controller=posts&action=index") // die(); $this->view->redirect("posts", "index"); } catch (ValidationException $ex) { // Get the errors array inside the exepction... $errors = $ex->getErrors(); // And put it to the view as "errors" variable $this->view->setVariable("errors", $errors); } } // Put the Post object visible to the view $this->view->setVariable("post", $post); // render the view (/view/posts/add.php) $this->view->render("posts", "add"); }
$userName = trim($_POST['userName']); $user = User::getByName($userName); if ($user == null) { $user = new User(); $user->setUserName($userName); $user->setRegistryDate(date('Y-m-d H:i:s')); $user->insert(); } $thread->setUserId($user->getUserId()); $thread->setCreated(date('Y-m-d H:i:s')); $thread->insert(); $post = new Post(); $post->setUserId($user->getUserId()); $post->setThreadId($thread->getThreadId()); $post->setCreated(date('Y-m-d H:i:s')); $post->setContent(trim($_POST['content'])); $post->insert(); header("Location: /index.php?thread=" . $thread->getThreadId()); die; } ?> <html> <head> <title>Форум</title> <meta charset="utf-8"/> </head> <body> <?php $view = View::getView(View::VIEW_MAIN); $view->show(); ?> </body>
<?php require_once 'autoloader.php'; echo "ok"; $query = new Create(); $query->createDatabase(); $user = new Post(); $user->setTitle('Etiam posuere'); $user->setPhotos('pics02.jpg'); $user->setContent('Pellentesque viverra vulputate enim. Aliquam erat volutpat. Pellentesque tristique ante. Sed vel tellus.'); $user->save();
public function testSave() { $post = new Post(); $post->setDate('2012-01-01 12:12'); $post->setTitle('New Post'); $post->setContent('New content'); $post->save('/tmp/'); $newPost = new Post('/tmp/2012-01-01-new-post.md'); $this->assertEquals('New Post', $post->getTitle()); $newPost->setTitle('change-url'); $newPost->save('/tmp/'); }
/** * Inserta un nuevo post en el muro del usuario actual si dicho usuario * inicio sesion previamente. * * @throws Exception Si no esta en sesion */ public function addPost() { if (!isset($this->currentUser)) { throw new Exception("Not in session. Editing posts requires login"); } $post = new Post(); if (isset($_POST["submit"])) { $post->setContent($_POST["content"]); $post->setDate(date("Y-m-d H:i:s")); $post->setAuthor($this->currentUser->getEmail()); try { // Valida el objeto Post $post->checkIsValidForCreate(); // Guarda el post en la base de datos $this->postDAO->save($post); // Redirecciona a la accion viewPost del controlador Post $this->view->redirect("posts", "viewPosts"); } catch (ValidationException $ex) { $errors = $ex->getErrors(); $this->view->setVariable("errors", $errors); } } // Carga los post en la vista y la renderiza $this->view->setVariable("posts", $this->loadPosts()); $this->view->render("posts", "inicio"); }