簡體   English   中英

從數據庫中提取信息並在HTML div中顯示

[英]Pulling the info from DB and displaying it in HTML div's

我對PHP還是很陌生,對MySQL也不太熟練。 我正在嘗試從數據庫中獲取信息,並使用唯一ID將信息放入不同的div中-例如,我的意思是:分配給ID 1的div將顯示該ID的條目,div = ID 2將執行該操作同樣的事情,依此類推。

到目前為止,這是我所擁有的:包含Article類的Article.php文件用於數據庫處理。 這就是我將信息從網站插入表格的方式。 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;
}

這就是我嘗試從數據庫中提取信息的方式:

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的內容:

在此處輸入圖片說明

我相信我已經正確地解釋了自己,感謝您的幫助,並在此先感謝您。 :)

我在這里簡化了一些事情,修復了代碼中的一些錯誤並進行了一些優化,但這只是入門的基本知識。

<?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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM