从数据库中提取信息并将其显示在HTML div

时间:2015-12-17 02:08:01

标签: php html mysql database

我对PHP很陌生,在MySQL中也不太熟练。 我正在尝试从数据库中获取信息并使用唯一ID将信息放入不同的div中 - 我的意思是,例如: 分配给ID 1的div将显示该ID的条目,div = ID 2将执行相同的操作,依此类推。

这是我到目前为止所拥有的: 包含Article类的Article.php文件用于DB处理。 这是我从网站上将信息插入表格的方式。 ID是自动递增的(我想在我的情况下这并不是一件好事);

public function insertInfobar()
{
    // Insert the infomartion into Infobar
    $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
    $sql = "INSERT INTO infobar ( title, subtitle, additional ) VALUES ( :title, :subtitle, :additional )";
    $st = $conn->prepare ( $sql );
    $st->bindValue( ":title", $this->title, PDO::PARAM_STR );
    $st->bindValue( ":subtitle", $this->subtitle, PDO::PARAM_STR );
    $st->bindValue( ":additional", $this->additional, PDO::PARAM_STR );
    $st->execute();
    $conn = null;
}

这就是我尝试从DB中提取信息的方式:

public static function getInfobar($id) 
{
    $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
    $sql = "SELECT title, subtitle, additional FROM infobar WHERE id=:id";
    $st = $conn->prepare ( $sql );
    $st->bindValue( ":id", $id, PDO::PARAM_INT );
    $st->execute();

    $list = array();
    while ( $row = $st->fetch() ) {
        $infob = new Article( $row );
        $list[] = $infob;
    }
    $conn = null;

    return ( array ( "results2" => $list));
}

然后,index.php处理前端,使用" switch"来调用函数。和" hompepage()"是默认情况:

function homepage() 
{
    $results2 = array();
    $data2 = Article::getInfobar((int)$_GET[""]);

    $results['pageTitle'] = "TESTPAGE";
    $results2['info'] = $data2['results2'];

    require( TEMPLATE_PATH . "/homepage.php" );
}

下一步,HTML。应根据表条目的ID显示信息:

<div class="infobar">
    <div class="table_row">
    <?php foreach ( $results2['info'] as $infob ) { ?>
    <div class="row_item1">
        <h1><?php echo htmlspecialchars($infob->title)?></h1>
        <p><?php echo htmlspecialchars($infob->subtitle)?></p>
        <p><?php echo htmlspecialchars($infob->additional)?></p>
        <p><?php echo htmlspecialchars($infob->id)?></p>
        <img src="" alt="">
    </div> 
    <?php } ?>
    <?php foreach ( $results2['info'] as $infob ) { ?>
    <div class="row_item2">      
        <h1><?php echo htmlspecialchars($infob->title)?></h1>
        <p><?php echo htmlspecialchars($infob->subtitle)?></p>
        <p><?php echo htmlspecialchars($infob->additional)?></p>
        <img src="" alt="">
    </div>
    <?php } ?>
</div>

我检查过,我只得到ID = 0.试图找出它但没有运气。 由于我得到ID = 0,我只能看到属于ID 0的内容:

enter image description here

我相信我正确地解释了自己,感谢任何帮助,并提前感谢你。 :)

1 个答案:

答案 0 :(得分:1)

我在这里简化了一些事情,修复了代码中的一些错误并对其进行了一些优化,但这只是让你入门的基础。

<?php

define('DB_DSN', /* your dsn info */ '');
define('DB_USERNAME', /* your username */ '');
define('DB_PASSWORD', /* your password */ '');

class Article {

    // public properties for the sake of simplicity...
    public $title;
    public $subtitle;
    public $additional;
    public $id;

    public function __construct( $row ) {
        // add the info from the database results to this object
        foreach($row as $key => $value){
            $this->{$key} = $value;
        }
    }
    public static function getInfobar($ids) {
        if ( !is_array($ids) ) { // we expect $ids to be an array of ids to retrieve
            // throw an exception, return null, whatever you want
        }

        // Set up the SQL statement
        $sql = "SELECT id, title, subtitle, additional FROM infobar ";
        // if we're getting certain ids, set up the query to search for them
        if ( !empty($ids) ) {
            // create a placeholder string of '?'
            // for example, if you have 3 ids, create a string like this: ?,?,?
            $idPlaceholders = str_repeat('?,', count($ids) - 1) . '?';
            // add the placeholders to the sql statement
            $sql .= "WHERE id IN (".$idPlaceholders.")";
        }
        else { // or if no ids given, just return the first 10 articles
            $sql .= "LIMIT 10";
        }

        $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
        $st = $conn->prepare ( $sql );
        if ( isset($idPlaceholders) ) { // if there are IDs, we'll execute the SQL with them
            $st->execute($ids);
        }
        else {
            $st->execute(); // otherwise just execute the SQL without any parameters    
        }

        // create article objects from the results
        $list = array();
        while ( $row = $st->fetch() ) {
            $list[] = new Article( $row );
        }
        $conn = null;

        return $list;
    }
}

$results2 = array();
$pageTitle = "TESTPAGE";

// check for ids in the query string, and check that it's an array
$ids = !empty($_GET["ids"]) && is_array($_GET["ids"]) ? $_GET["ids"] : array();
$results2['info'] = Article::getInfobar($ids);

?>

<html>

<head>
    <title><?php echo $pageTitle; ?></title>
</head>

<body>
    <!-- an example of sending info in a query string that will get parsed into a PHP array in $_GET -->
    <?php if ( empty($ids) ) { ?>
        <a href="?ids[]=0&ids[]=2">Get only articles with ID 0 and 2</a>
    <?php } else { ?>
        <a href="?">Get the first 10 articles</a>
    <?php } // end if ( empty($ids) ) ?>    


    <!-- a simple example of displaying all the results -->
    <table class="infobar">
        <thead>
            <tr>
                <th>id</th>
                <th>title</th>
                <th>subtitle</th>
                <th>additional</th>
            </tr>
        </thead>

        <tbody>
            <?php foreach ( $results2['info'] as $infob ) { ?>
            <tr>
                <td><?php echo htmlspecialchars($infob->id); ?></td>
                <td><?php echo htmlspecialchars($infob->title); ?></td>
                <td><?php echo htmlspecialchars($infob->subtitle); ?></td>
                <td><?php echo htmlspecialchars($infob->additional); ?></td>
            </tr>
            <?php } // end foreach ( $results2['info'] as $infob ) ?>
        </tbody>
    </table>
</body>

</html>