Php pdo:显示数据库主题

时间:2018-03-13 15:01:26

标签: php mysql twitter-bootstrap pdo

我需要一些帮助,找出如何在我的网站上显示mysql(phpmyadmin)数据库中的所有主题。

This is how it looks like now

代码是:

<section class="col-md-4 connectedSortable">
    <!-- TABLE: LATEST ORDERS -->
        <div class="box box-info">
            <div class="panel panel-default">
               <div class="panel-heading main-color-bg">
                  <h3 class="panel-title">Topics</h3>
               </div>
               <div class="container-fluid">
                  <div class="row content">
                    <ul class="nav nav-pills nav-stacked">
                       <li class="active"><a href="#section1">Home</a></li>
                       <li><a href="#section2">Friends</a></li>
                       <li><a href="#section3">Family</a></li>
                       <li><a href="#section3">Photos</a></li>
                    </ul><br>
                  </div>
                </div>
              </div>
        </div><!-- /.box -->        
</section><!-- right col -->

我希望此列表成为数据库外的主题列表

How the database looks like

这是我的config.php:

<?php  
date_default_timezone_set('Europe/Amsterdam');

error_reporting(E_ALL & ~ E_DEPRECATED);
ini_set('display_errors','ON');

$CONFIG = array();
$CONFIG['root']         = '####';
$CONFIG['rootwebsite']  = '####';
$CONFIG['website']      = '####';

$CONFIG['dbhost']       = 'localhost';
$CONFIG['dbuser']       = '####';
$CONFIG['dbpass']       = '####';
$CONFIG['dbdatabase']   = 'tom';
?>

我尝试了什么:

class Forum
    {
    private $dbh; //dbh = database handler.
    public function __construct($database)
    {
    $this->dbh = $database;
    }

    /* function that gets the main forum board */
    public function getForum()
    {
    $query = $this->dbh->prepare('SELECT * FROM `topics` ORDER BY `id` ASC');
    $query->execute();
    $results = $query->fetchAll();

    foreach( $results as $row ){
      print_r( $row );
    }
    }
}

1 个答案:

答案 0 :(得分:0)

从PDO的角度来看:

<?php
// Connect to DB
try {
$yourdsn = 'mysql:dbname=<YOURDBNAME>;host=<YOURDBHOST>;
$data = new PDO($yourdsn, $youruser, $yourpassword);
$data->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$data->exec("set names utf8");
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}

然后查询你的表

$sql = "SELECT * FROM topics ORDER BY id DESC";
$topics = $data->prepare($sql);
$topics->execute();
$tops = $topics->fetchAll(PDO::FETCH_OBJ);

最后循环结果为HTML模板

<? foreach($tops as $top):?>
<h1><?=$top->onderwerp?></h1>
<p><?=$top->omschrijving?></p>
<? endforeach;?>