将数组对象从数据库转换为字符串

时间:2018-12-04 13:35:00

标签: php arrays database string

我目前正在编写博客,以获取有关php的经验。

在edit.php中,如果一个帖子有一个类别,我想给出一个类别。 这是edit.php

    <div class="categories-heading">
    <?php if (!empty($entry->c_Id)): ?>
      <div class="category-heading">
        <h3>Category: <?php echo e($categoryFromId); ?></h3>
      </div>
      <div class="category-heading">
        <h3>change category</h3>
      </div>
    </div>
    <form method="post">
      <div class="categories-post-edit">
        <?php foreach($categories as $cat): ?>
          <div class="category-post-edit">
            <input type="radio" name="category" value="<?php echo e($cat->id); ?>">
              <label> <?php echo e($cat->category); ?></label>
            </input>
          </div>
        <?php endforeach; ?>
      </div>
    </form>
  <?php else: ?>
    <div class="category-heading">
      <h3>choose category</h3>
    </div>
  </div>
  <form method="post">
    <div class="categories-post-edit">
      <?php foreach($categories as $cat): ?>
        <div class="category-post-edit">
          <input type="radio" name="category" value="<?php echo e($cat->id); ?>">
            <label> <?php echo e($cat->category); ?></label>
          </input>
        </div>
      <?php endforeach; ?>

这是edit()中功能PostsAdminController.php的一部分,与此相关:

if(!empty($_POST['title']) AND !empty($_POST['subheading']) AND 
!empty($_POST['content'])
AND !empty($_POST['category'])) {
  $entry->title = $_POST['title']; 
  $entry->subheading = $_POST['subheading'];
  $entry->content = $_POST['content'];
  $entry->c_Id = $_POST['category'];

  $this->postsRepository->update($entry);

  $savedSuccess = true;
 }
 $categoryFId = $this->categoryRepository->oneCategory($entry->c_Id); 

 $categoryFromId = $categoryFId['category'];
 var_dump($categoryFromId);

 $this->render("post/admin/edit", [
  'entry' => $entry,
  'savedSuccess' => $savedSuccess,
  'categories' => $categories,
  'categoryFromId' => $categoryFromId
 ]);
}

这是oneCategory中与数据库交互的函数CategoryRepository.php

public function oneCategory($id)
{
 $table = $this->getTableName();
 $model = $this->getModelName();

 $stmt = $this->pdo->prepare("SELECT `category` FROM `$table` 
 WHERE id = :id"); 

 $stmt->setFetchMode(PDO::FETCH_CLASS, $model);
 $oneCategory = $stmt->fetch(PDO::FETCH_CLASS);

 return $oneCategory;
}

oneCategory()给出一个数组,无论我在查询中放置SELECT *还是SELECT category,这就是为什么之后将$categoryFId['category']放入变量的原因。

它可以工作,但是我认为必须有一种更简便或更快捷的方式(例如特殊功能等),我只是没有找到要搜索的内容

0 个答案:

没有答案