College Student needs help resolving php/database problem!

Hi, so I’m new to PHP, and I’m taking a college class on it. However the instructor is not particularly helpful with his instructions on the assignment, and tends to give vague answers on how to find the solutions to issues we have.

Here is the basic problem. I have a database, and 2 seperate php pages. One is “index.php”. The other is “home.html.php”.

My problem, is the picture that I provided. I’ve tried coding this a few different ways, but for the life of me I am hung up on how to resolve the problem I’m facing. And since the instructor isn’t being helpful, I need someone to actually give me a helping hand in resolving this problem.

index.php: Supposed to connect to my xampp database, and pull rows from a certain table in the database.


<?php
try
{
  $pdo = new PDO('mysql:host=localhost;dbname=seanropp_pht_db', 'seanropp_pht_user', 'password');
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $pdo->exec('SET NAMES "utf8"');
}
catch (PDOException $e)
{
  $error = 'Unable to connect to the database server.';
  include 'home/error.html.php';
  exit();
}

try
{
  $sql = 'SELECT title, description, image FROM content';
  $result = $pdo->query($sql);
}
catch (PDOException $e)
{
  $error = 'Error fetching page: ' . $e->getMessage();
  include 'home/error.html.php';
  exit();
}

while ($row = $result->fetch())
{
  $content[] = array(
      'title' => $row['title'],
      'description' => $row['description'],
      'image' => $row['image'],
  );
}

include 'home/home.html.php';

home.html.php: HTML page witht he “header”, “body”, “main”, etc. elements in it. PHP coding in here is the problem.


<!DOCTYPE html>

<html lang="en">
<head>
  <title>Portland Historical Tours</title>
  <meta name="description" content="Portland Historical Tours has offered three Portland Tour options for over 33 years: the Downtown Tour, the Landmarks Tour and the Growth Tour.">
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href=project.css>
  <link href='https://fonts.googleapis.com/css?family=Cinzel' rel='stylesheet' type='text/css'>
    <!--[if lt IE 9]>
      <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
</head>
<body>
  <div id="wrapper">
      
    <?php include 'includes/header.inc.php'; ?>
      
    <?php include 'includes/navigation.inc.php'; ?>
      
    <main>
        
        <?php 
        foreach ($content as $contents): ?>
            <?php
                echo "<img src=" . "$contents" . "width='850' height='389'>";
                echo "<h1>" . "$contents" . "</h1>";
                echo "<p>" . "$contents" . "</p>";      
        ?>
        
       
<!-- TEMPORARY Block out, use for referance, may need to delete later

        <a href="tours.php"><img src="images/downtown.png" alt="Portland Historical Tours" width="850" height="389"></a>
        <h1>How did we get started?</h1>
        <p>
          We have such a passion for the city we live in. For over 33 years we have offered tours for Portland visitors and residents alike through our family business. Having family in Portland since the early 1900's has allowed us to build tours out of insight over 100 years. We are confident you will love any of our Portland tours with the help of our generous guides. We offer three tours: the Downtown, the Growth, and the Landmarks tour. Our favorites are the Downtown and Landmarks but with Portland's current growth we are selling out our Growth tours.<br><br>We hope to meet you soon! Let us know if you have any questions by visiting the <a href="contact.html">Contact page.</a><br><br>Thank you!
        </p>
-->        
      <!--
        <a href="tours.html"><img src="images/downtowntour.png" alt="Portland Historical Downtown Tour" width="850" height="481"></a>
        <div id="source"><p>(City of Portland Archives)</p></div>
      <a href="tours.html"><img src="images/growthtour.png" alt="Portland Historical Growth Tour" width="850" height="481"></a>
        <div id="source"><p>(City of Portland Archives)</p></div>
      <a href="tours.html"><img src="images/landmarkstour.png" alt="Portland Historical Landmarks Tour" width="850" height="481"></a>
        <div id="source"><p>(City of Portland Archives)</p></div>
        -->
      
        <?php endforeach; ?>
        
    </main>
      
    <?php include 'includes/footer.inc.php'; ?>
      
  </div>
</body>
</html>

So I figured I should post the instruction from the instructor on the part of the assignment that we have to do.

[ul][li]Add a foreach loop php island below the opening ‘’ tag. This loop will display the 1 record generated by the SELECT query. That record contains 3 values, one for the image, one for the title ‘

’ and one for the paragraph ‘

’.[/li]

[li]Using the record values generated by the SELECT query, replace the image src, h1 text and all the ‘

’ text with the results generated by the while loop in the root index.php page.[/li]

[li]Add an endforeach php island above the closing ‘’.[/li][/ul]

Here is the basic problem. I have a database, and 2 seperate php pages. One is "index.php". The other is "home.html.php".
[b]What is the problem???[/b]
My problem, is the picture that I provided.
[b]What is the problem???[/b]
for the life of me I am hung up on how to resolve the problem I'm facing
[b]What is the problem???[/b]
I need someone to actually give me a helping hand in resolving this problem.
[b]What is the problem???[/b]
PHP coding in here is the problem.
[b]What is the problem???[/b]

How about telling us what the problem is. ::slight_smile:

You are just getting your feet wet, so I will be nicer than usual.

You are all over the board. Your foreach loop for instance, printing Array?
[php]
foreach ($content as $contents):
echo “<img src=’{$contents[‘image’]}’ width=‘850’ height=‘389’>”;
echo “

{$contents[‘title’]}

”;
echo “

{$contents[‘description’]}

”;
endforeach;[/php]

Notice I used the keys defined. You are not doing so. Also note, that I am not hoping in and out of PHP or concatenating strings together. Two things you are doing here:
[php] foreach ($content as $contents): ?>
<?php
echo “<img src=” . “$contents” . “width=‘850’ height=‘389’>”;[/php]

Lastly, HTML is not XML. So, you cannot define your own elements like you are doing with main.

[php]

… removed for brevity

 </main>[/php]

I would suggest using a Template engine, such as Smarty (Which I use) or Twig. That way you can have multiple templates that utilize the same php and most people know HTML with a little bit of programming knowledge. That way you could technically have a person who isn’t a guru in PHP be able to design and develop a website as long as the PHP has been develop by someone. Curly brackets denote Smarty variables, if statements and/or loops. An added feature is an additional layer of security.

An Example of one of my templates in Smarty:
[php]{extends file=“general_page_template.tpl”}
{block name=meta}




{/block}
{block name=title}
{$basename|escape}
{/block}
{block name=body}



{include file=‘cms_template_inc.tpl’ column=“left” online_id=$online_id}

    </div>            
    <div id="blogInfo" class="span4">
        <h2>The Daily Blog</h2>
        {nocache}
            <form id="selectBlog" action = "{$basename}" method = "post">
                <input type="hidden" name="action" value="selection">
                <input id="statusCheck" type="hidden" name="status" value="{$login_status}">
                <label>Select User</label>
                <div id="selectUser">

                    {html_options id="selectBtn" name=user_id options=$myOptions selected=$mySelect nocache}

                </div>
                <input id="blogSubmitBtn" type = "submit" name = "my_submit" value = "submit button">
            </form>
        {/nocache}
        <p>This is a FREE blog that anyone can use and you can keep it private for your eyes only. Note, I have the right to check the private posts after all I am running this website, so don't write anything of  a confidential nature. Though hopefully you will make it public for everyone to see. To write a new post to your blog you must be logged in and then simply click the button below (it will show up when you're logged in). I have made it where you can change your privacy mode right here on this blog page. </p>

        {nocache}
        {if $login_status}
            <a id="blogButton" href="create.php">new blog</a>
            <form id="private"  action="{$basename}" method="post">
                <h2>Private Posts is Turned </h2>
                <div class="slideThree">
                    <input type="hidden" name="action" value="enter">
                    <input id="slideThree" type="checkbox" name="private"  value="on" {$checked}>
                    <label class="radioLabel" for="slideThree"></label>                        
                </div>
                <input id="privateBtn" type="submit" name="enter" value="change">
            </form>
        {/if}
        {/nocache}

    </div>
</div>

{/block}
{block name=footer}

©2017 John R. Pepp




{/block}[/php]

You can call other templates within a template and even have a general template that gives the general design of the entire website.

all you have to do is pass the variables and/or arrays to the template that you call in your php ->

[php]<?php

require_once ‘…/private/initialize.php’;

use Library\Read\Read;

$selection = [];
$page_name = ‘blog.php’;
$username = \NULL;
$posts = new Read(); // Create an instance of the Read class:
if ((isset($_SESSION[‘user’]->id)) && !$posts->checkCMS($_SESSION[‘user’]->id)) {
header(“Location: create.php”);
exit();
}
if (isset($_SESSION[‘user’]->id)) {
$username = $_SESSION[‘user’]->username;
$user_id = $_SESSION[‘user’]->id;
$smarty->assign(‘security_level’, $_SESSION[‘user’]->security_level);
$login_status = TRUE;
$online_id = $_SESSION[‘user’]->id;
if ($_SESSION[‘user’]->private === ‘yes’) {
$checked = ‘checked’;
} else {
$checked = \NULL;
}
} else {
$user_id = getSysopId();
$online_id = \NULL;
$login_status = FALSE;
$smarty->assign(‘security_level’, \NULL);
$checked = \NULL;
}

$enter = filter_input(INPUT_POST, ‘action’, FILTER_SANITIZE_FULL_SPECIAL_CHARS);

if (isset($enter) && $enter === “enter”) {

$private = filter_input(INPUT_POST, 'private', FILTER_SANITIZE_FULL_SPECIAL_CHARS);

if ($private === 'on') {
    $value = 'yes';
} else {
    $value = 'no';
}

changePrivacy($value);

}

$submit = filter_input(INPUT_POST, ‘action’, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
if (isset($submit) && $submit === ‘selection’) {
$user_id = filter_input(INPUT_POST, ‘user_id’, FILTER_SANITIZE_NUMBER_INT);
}

$user_info = getUserInfo();
/*

  • Format the array in the proper format
  • with the key being the user’s id and the
  • value being the user’s name. For example:
  • [ 134 => ‘Gimli’] with 134 being the key and
  • Gimli being the value.
    /
    foreach ($user_info as $info) {
    //echo 'info id ’ . $info[‘id’] . ’ info username ’ . $info[‘username’] . ’ info private ’ . $info[‘private’] . “
    ”;
    if ($posts->checkCMS($info[‘id’]) && ( $info[‘private’] === ‘no’ || ( isset($_SESSION[‘user’]) && $_SESSION[‘user’]->security_level === ‘sysop’ ) )) {
    $selection[$info[‘id’]] = $info[‘username’];
    }
    /
    This could be combine with the above, but this is easier to follow */
    if (is_logged_in() && $_SESSION[‘user’]->id === $info[‘id’]) {
    $selection[$info[‘id’]] = $info[‘username’];
    }
    }
    //echo “
    ” . print_r($user_info, 1) . “
    ”;
    $smarty->assign(‘myOptions’, $selection); // Assign the selection array to the option of the select element:
    $smarty->assign(‘mySelect’, $user_id); // Assign current id as selected in the options portion of the select element:

/*

  • Read User’s Blogs
    */
    $content = $posts->readBlog(“blog.php”, $user_id); // Read all the posts of the current value of the $user_id variable:

$smarty->assign(‘pagename’, $pageName);
$smarty->assign(‘user_id’, $user_id);
$smarty->assign(‘online_id’, $online_id);
$smarty->assign(‘basename’, $basename); // Title of Page:
$smarty->assign(‘login_status’, $login_status); // Login Status:
$smarty->assign(‘username’, $username); // User’s login name if logged in:
$smarty->assign(‘content’, $content); // CMS Threads for index.php:
$smarty->assign(‘column’, “left”);
$smarty->assign(‘checked’, $checked);
$smarty->display(‘blog_template.tpl’); // Desplay the blog HTML template:[/php]

Sponsor our Newsletter | Privacy Policy | Terms of Service