从PDO关联数组中获取数据

时间:2017-04-18 03:22:49

标签: php html

我有一个搜索页面(search.php),可以找到"笑话"由特定作者创作。

    <?php

spl_autoload_register(function ($class) {
    include_once($class.'.php');
});
  $obj=new oopCrud;

      if(isset($_REQUEST['search'])){
      extract($_REQUEST);
      $obj->search($authorid,"joke");}

}
?>
    <body>
     <div class="wrapper">
        <h1 class="main_heading">Search Jokes</h1>
        <form action="searchform.html.php" method="post">
            <p>View jokes satisfying the following criteria:</p>
            <div>
                <label for="author">By author:</label>
                <select name="authorid" id="authorid">
            <?php foreach($obj->showData("author") as $value){
            extract($value);
            echo @<<<show
            <option value=$id>$name</option>
show;
    }
  ?>
        </select>
            </div>
                <input type="submit" name="search" value="search" class="btn">
            </div>
        </form>
        </div><!-- end of wrapper -->

在我的控制器文件(oopCRUD.php)中,笑话被定位并存储在关联数组中,如下所示:

公共功能搜索($ authorid,笑话){

$sql="SELECT * FROM joke WHERE authorid = :authorid";
$q = $this->conn->prepare($sql);
$q->execute(array(':authorid'=>$authorid));
$data = $q->fetch(PDO::FETCH_ASSOC);
//print_r($data); This has shown that there is the required data stored in the array.
//exit();
return $data;

}

我想将此数据发送到searchresults.php页面以显示结果。如何在searchresults.php页面上发送或检索数据集然后显示它?我不想直接使用jQuery / AJAX等php / html。

我正在使用PDO创建查询并使用面向对象的编程方法。

1 个答案:

答案 0 :(得分:0)

获取页面刷新数据(提交):

$ results = $ obj-&gt; search($ authorid,“joke”);

加载数据

并在您的HTML代码中......

<select name="authorid" id="authorid">
<?php 
     if($results){ 
          foreach($results as $result){ 
               foreach($result as $key=>$val) { 
                   ?>
                       echo "<option value={$val['id']}>{$val['name']}</option>"
                   <?php
               }
          }
     }
?>

我不确定你要对结果做什么,以及 - &gt; showData函数。试试这是否有帮助。

===

MultiDimensional Array to Table ...你也可以使用echo "<table>",如果你不想每次都关闭php标签。

<?php

$results = array(
            array('jokeid' => 13, 'joketext' =>'Why did the chicken cross the road? To avoid getting roasted.', 'jokedate' => '2017-04-15', 'authorid' => 1 ), 
            array('jokeid' => 16, 'joketext' => 'This is test joke2', 'jokedate' => '2017-04-16', 'authorid' => 1 )
        );

if($results)
{
    ?><table><?php
    foreach($results as $result)
    {
        ?><tr><?php
        foreach($result as $key=>$val)
        {
            ?><td> <?php echo $val; ?> </td> <?php
        }
        ?></tr><?php
    }
   ?> </table> <?php
}
exit;
?>