Ruslan
Ruslan

Reputation: 361

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

I am quite new to PHP and not too skilled in MySQL as well. I am trying to get the info from the database and place that info into different div's using the unique ID's - what I mean is, for example : div assigned to ID 1 will display the entry for that ID, div = ID 2 will do the same thing and so on.

Here's what I have so far: Article.php file which contains the Article class is used for the DB handling. This is how I insert the info to table from the website. ID is on auto-increment (I guess that's not really a good thing in my case);

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;
}

And this is how I try to pull the info from 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));
}

Then, the index.php handles the front-end, the functions gets called with the "switch" and the "hompepage()" is the default case:

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

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

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

Next step, the HTML. The info should be displayed depending on the ID of the table entry:

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

I checked, that I only get the ID= 0. Trying to figure it out but no luck. Since I get the ID = 0, I can only see the contents belonging to ID 0:

enter image description here

I believe I explained myself correctly, any help appreciated and thank you in advance. :)

Upvotes: 0

Views: 394

Answers (1)

Chris
Chris

Reputation: 4446

I simplified things a bit here, fixed some of the errors in your code and optimized it a little bit, but it's just something basic to get you started.

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

Upvotes: 1

Related Questions