Problem - I've created a DB Connection, I've queried the DB, and I've turned the results into an associative array. Displaying the SQL Data using PHP is the trouble I'm having. I've managed to display it in a basic way, however my aim is for this information to display as a 'News Column' down the side of the page, and therefore I need the data to be inserted into Divs for me to be able to manipulate.
Attempt thus far - As one can see below, the presentation of this attempt to display my data is cringeworthy. However in this way I did manage to distinguish the types of headings for each piece of data.
echo "<h2>" . $row["title"]. "</h2><h3>Date: " . $row["dateTime"]. "</h3><h4>Passage: " . $row["passage"]. "</h4><br>";
HTML For Current Webpage:
http://i.imgur.com/9U1TWkd.png (What my 'News Column' looks like)
http://i.imgur.com/1tgA0sx.png (My HTML Code I want Data to be inputted into) - The aim is for someone to be able to complete this form (http://i.imgur.com/0xMnOVB.png) and the data to go into the DB (done this), and display in the column with the 'Title' appearing in the right place, same with 'Date' and finally with the 'Passage'.
What I've Found Online:
I dislike wasting people's time so I've spent a few hours searching online. Thus far I've found mostly people creating HTML Tables with their SQL Data, which is great and all, however I've not found anyone who's using Divs/Headings/Paragraphs etc...
My CSS:
I have a CSS File which I'm retrieving (or whatever the term is) via HTML Code which is working (so far).
Interestingly, you seem to have all the components you need: An example of how the markup (the HTML) needs to be outputted and the DB query and data to inject into it. Unless I'm missing something (it's always possible!), then all that remains is for you to glue the two together.
Assuming the form represented in your most recent graphic is generated within a .php file you can either pre-build a giant variable containing all the markup necessary to render your output, or write some static HTML and insert only the dynamic elements using native PHP (PHP is itself a templating language of sorts).
Using the latter method you'd do something like the following (forgive different CSS class names and tag hierarchy, I can't copy/paste from a PNG :-)
<div class="wrapper">
<?php foreach($myResult as $row): ?>
<div class="article>
<h3><?php echo $row['Title']; ?></h3>
<div class="date"><?php echo $row['Date']; ?></div>
<p><?php echo $row['Body']; ?></p>
<div>
<?php endforeach; ?>
</div>
Related
I am creating breadcrumbs on my simple site.
I have some helper classes. I use them like this (just example):
$Breadcrumbs = new Breadcrumbs();
$Breadcrumbs->add(new Breadcrumb("/", "page1"));
$Breadcrumbs->add(new Breadcrumb("/", "page2"));
$Breadcrumbs->add(new Breadcrumb("/", "page3"));
$breadcrumb->show(); returns this:
<ol class="breadcrumb">
<li>page1</li>
<li>page2</li>
<li class="active">page3</li>
</ol>
So, in my project I have some switch-case constructions in which I include some files.
In this files I am using $breadcrumbs->add(...). This code:
<div class="container body">
<? $Breadcrumbs->show();?>
<?
$page = isset($_GET['page']) ? $_GET['page'] : null;
switch($page):
case "suppliers":
require_once($DOCUMENT_ROOT."/modules/suppliers.php");
break;
default:
require_once($DOCUMENT_ROOT."/modules/default.php");
break;
endswitch;
?>
<? $Breadcrumbs->show();?>
</div>
gives me this result:
Well, it works like it must work. I am using $breadcrumbs->add(...) in require files after I called $breadcrumb->show() first time thats why 1st call returns blank result. 2nd call of show() is after all breadcrumbs are added, so it returns fine result.
The questions is how to output breadcrumbs before switch blocks but with right content. Maybe I need a buffer or idk?
This is a good example of why it is such a good idea to separate out logic from presentation: you have a nice abstraction for crumb links, but can't use it properly because your other code is outputting as it goes along, rather than working with abstract data.
Obviously, you could throw away your current structure and port both logic and display directly into a new framework, but assuming you want to migrate from where you are now, here's one approach:
Create an object or array that represents the "result" of whatever module is called. Replace all current use of echo or ?> with concatenation to a string called something like $results['generic_output']. This is effectively like buffering your output, and is enough to let you use your existing abstractions like $breadcrumbs at any time. At this stage, your "template" would consist mostly of echo $results['generic_output'], plus the boilerplate header and footer which is probably already gathered in one place.
Start breaking down the output into sections. Particularly look for sections which are similar on multiple pages. For instance, if you have a "sidebar" with different content on each page but similar styling, make a $results['sidebar_content'] with just the content of that sidebar; the boilerplate to lay it out can then go into your template, and you've reduced the amount of code duplication.
Make the data you pass to the template increasingly abstract, with the goal of eventually having no HTML outside of the template(s). For instance, maybe the sidebar is made up of panels; you might start with an array of HTML blocks, one for each panel, but then turn it into an array of objects based on the actual data being displayed (say, a special offer, or the customer's current basket), with a set of templates for handling different kinds of panel. Eventually, it should be theoretically possible to build a plain-text version of your site with no HTML, just by changing the template layer, and none of the original modules.
The final step is to separate decisions about what to show from decisions about what to do. Continuing with my imaginary sidebar, your template could always receive the current basket as a general variable for use somewhere on the page, rather than as "sidebar item 1". This allows you to completely separate the actions that led into a page from the output that eventually results.
I would like to stress that this is not the way to a perfect framework, or the definitive solution to your situation, but it's one way of organising existing code (and existing thinking) in the right direction.
In the above, the "templates" could just be a set of PHP files using ?> or echo to produce the output, or it could be a dedicated templating system such as Smarty or Twig. Indeed, the point of the separation is that you could change your mind on that front later, because the result of the code modules would be an array of data to be displayed, which is just what Smarty or Twig would need as input.
UPDATE
I've solved by myself this problem. It wasn't a problem at all, just because lack of experience.
Everything went from a misunderstanding of the $_GET variable and for what can be used, and PHP data types as well. When I did read twice the PHP documentation, I understood that it is actually an array and I could put several variables and pass several parameters through it, as it is persistent.
From there, the rest was piece of cake. With a single include and a bunch of functions I can do all the database petitions and output them as I want!
I'm glad I've been able to solve it by myself, and thanks to Passerby, who made me think about how I was managing the $_GET variable.
I had to redo this question because last one was a dull brick of text. Let's simplify.
Let's say I have a fruit DB with 'n' items. The cols are the following:
Name of the fruit.
Country of origin.
Color.
On the index.php I have sidebar.php with links and a content.php with some text into it. Like this:
<!--html code here-->
<?php include('includes/content.php') ?>
<?php include('includes/sidebar.php') ?>
<!--more html code here-->
The links of the sidebar.php are like these:
Browse by country
Browse by color
etcetera.
searchDB.php is generated with the same layout than index.php with this difference:
<!--html code here-->
<div id="content">
<?php include('functions/fruit_list.php') ?>
</div>
<?php include('includes/sidebar.php') ?>
<!--more html code here-->
inside fruit_list.php there's a script that shows all countries into the content <div>
once you click on 'browse by country'. It generates some hyperlinks as well which I'm unable to manage or figure how to link them to a function, or somewhere that allows me to go one level deeper (for instance if you click into 'Japan', I'd like to list all fruits from Japan).
If possible, the new generated list (all fruits from Japan), should be on the same content div.
Any ideas? Thoughts? I have a wrong approach to do this?
This is probably going to be quite an easy question for everyone, and I have tried following and understanding tutorials, but I just cant get my head around it!!
Ok so for University me and my peers are creating a student assesment system, my task is to create a results view page.
Basically I have been given a file called index.php which has a template background with a header and footer thats just looks like a normal web page. I need to be able to display results from a table from a database (I dont have yet but can create a test to test it) that has data into a certain position of that index.php page.
I have phpadmin installed and have tried creating a test database and table to insert in, but it just doesnt work when i follow tutorials like this one http://www.siteground.com/tutorials/php-mysql/display_table_data.htm , i just cant understand it, which im sure if my fault!!!
Someone else is writing the query's ill need, but firstly im just trying to understand how I even do this, and how i tell it to go to the index.php page, and where to place the table on that page.
This is the php code for the index.php file if i open it in notepad ++
<?php
/*use template to create pages*/
include('templates/header.html');
include('templates/topMenu.html');
?>
<div id="contentwrap">
<div id="content">
<div style="clear: both;"> </div>
</div>
<?php
require_once('templates/sidebarStudent.php');
?>
<div style="clear: both;"> </div>
</div>
<?php
include('templates/footer.html');
?>
So my question is do I just enter some code somewhere in this index.php file that tells it where to get the database and table from? and how do I tell it where to position the table in the page, or do I have to create seperate php files for this?
Please help! :(
If you were able to create some sort of test database, then you can use this basic code example to get up and running. You can put this inside one of those <div> tags to get the content to show up where you need it. Make sure you update the parameters below for your database username, password, database name, etc.
<?php
$link = mysql_connect('localhost', 'db_user_name_here', 'db_password_here');
mysql_select_db('db_name_here', $link);
$result = mysql_query('SELECT * FROM table_name_here');
while ($row = mysql_fetch_assoc($result)) {
echo $row['column_name_here'] . "<br>";
}
mysql_close($link);
?>
If you still have trouble, then you'll need to make sure you have a proper database user, a database, and a table inside that database. It might be best to look for a tutorial because it will likely walk you through the steps necessary better than I can do here.
Excellent question.
It rarely occurs when someone even bother with it.
Most of time the usual scenario for the PHP script is just to put everything into one perfect mess.
Yes, you have to always use separate files for the PHP and HTML code (business and presentation logic to be correct).
The guy who is writing queries have to put all the code into separate file which collects all the data into some variables which have to be passed into template file.
Then his code has to set the name of the file which contains the page template.
And finally call your main page template.
So, the index.php file should contain NO HTML code, but PHP only:
<?
//include settings, connect to database etc.
include dirname($_SERVER['DOCUMENT_ROOT']).'/cfg/settings.php';
//getting required data
$DATA = db::getarr("SELECT * FROM links");
// setting title for using in the main template
$pagetitle = "Links to friend sites";
//etc
//set page template filename
$tpl = "links.tpl.php";
//and then finally call a template:
include "main.tpl.php";
?>
where main.tpl.php is your main site template, including common parts, like header, footer, menu etc (there is no need to have header and footer in the separate files):
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My site. <?=$pagetitle?></title>
</head>
<body>
<div id="page">
<? include $tpl ?>
</div>
</body>
</html>
and links.tpl.php is the actual page template:
<h2><?=$pagetitle?></h2>
<ul>
<? foreach($DATA as $row): ?>
<li><?=$row['name']?></li>
<? endforeach ?>
<ul>
Eventually you may come to more complex designs, like with front controller one, but for the first site this one is both easy and powerful.
Since a couple of days I am working on some WordPress Page for a friend of mine who is owning a company for time work. They are working with some software, that is, at the end, producing a HTML file with some tables, spans and stuff. This file actually is a template, they use to search for new employees. To make sure, they don't have the work of setting up the employment ad twice (working with 2 different web sites), I offered them, to set up a field to enter the HTML sourcecode, containing CSS, Tables, Spans and a lot of "dirty" stuff. Since tables are not
very search enginge optimized (don't let's talk about W3C), I told them to use divs instead. - what a mistake I made :)
Anyway: I used some lines of code like:
<?php
include('simple_html_dom.php');
$html = new simple_html_dom();
$html->load_file('http://www.prophiler.de/rentaman2/stellenanzeige');
foreach($html->find('SPAN.SHeadcompany') as $a)
{
$a->class = null;
$a->innertext;
echo $a->innertext = '<div class="head1">' . $a->innertext . '</div>';
}
... continue with all SPAN classes...
?>
to parse the file and write the contents back into div classes.
The problem I have is to call AND parse the custom field actually. This is why I called the HTML file through an invisible WordPress Page. This was for presentation only. Now I would like to call the field value directly and append it to the parser. I don't get it, since I am pretty new to PHP.
Is anybody out there, able to give me some hints on how to handle it?
I'm relatively new to php, and I'm working on a project using a mysql database. The project consists of users being able to write posts, which are then shown in a list format. The problem is, the posts are shown in different locations on the site, like the index (main) page, and the users profile page. Similar to twitter if you're confused. My question is, what is the best way to display the posts? Currently I'm using a class that I created. It has functions to retrieve posts from the database, save them all in a multidimensional array. Then another function in the class formats the entire list using foreach, and then returns the formatted HTML list of posts. All I have to do is echo what is returned. But I read somewhere that it's bad practice to write functions (especially class functions) that output HTML. What would be the best way to do this, without having to rewrite the same code on every page the posts are shown. Is it really bad practice to use HTML in functions?
Example...
a profile page looks something like this.
<
require('class.php');
require('header.php');
$profile = new Profile();
$userProfile = $profile->GetUserProfile($userID);
echo $userProfile;
$class = new Posts();
$posts = $class->GetUserPosts($userID);
echo $posts;
require('footer.php');
?>
And the main page looks something like this
<
$class = new Posts();
$posts = $class->GetAllPosts();
echo $posts;
?>
where the profile class would take a user id and output the users profile, already formatted in HTML.
And the posts class has functions to return a determined number of posts already formatted in an HTML list.
Should I keep everything in the class, or is there a better way?
Thanks
Well, if you're not using an MVC framework of some kind, then I would say that having functions that output HTML isn't going to kill anyone.
Generally however, it's helpful to separate HTML from logic, and this is usually done by creating an HTML template and template fragments with interspersed PHP. Something like this:
<div>
<h1><?php echo $title; ?></h1>
</div>
You could then set up a $title variable (and others), and include('title_fragment.php') to output that bit of HTML. You can extend this to work with entire pages, making it so that your code only has to deal with small amounts of data that get passed to the template.
When it comes time to make changes to the page layout or look, you don't have to go hunting through the code to find the bits of generated HTML... you can go straight to the template files.
This is important for maintainable design as well as code, and it makes it easier to produce other output types later on.
With PHP, one of the simplest libraries for separating the two is Smarty templates. Using Smarty (or any other templating library), you can write an HTML file with the layout and some simple loops or other constructs, and then render that template using a data structure. At the very least, I would suggest altering your class to utilize a template and produce output that way, rather than a mish-mash of print or echo statements with a bunch of HTML in them.
I'd even shy away from #zombat's solution of echo statements in HTML fragments, they quickly become ugly.
Example Smarty template to achieve something like what you want:
{section name=i loop=$posts}
<li>{$posts[i].author} — {$post[i].text}</li>
{/section}
And some PHP supporting code:
// Instantiate Smarty object
$smarty = new Smarty();
// Assign a hash of data
$smarty->assign('posts', array(
array('author' => 'Jim', 'text' => 'Hi this is my post!'),
array('author' => 'Sally', 'text' => 'My first post to the system')
)
);
// Use the file with the above template in it
$smarty->display('posts.html');
The part where you assign data to the template should probably be done via some programmatic means to convert your list of class objects into a list of hashes.
This way you can easily change the way the output looks just by editing the HTML template and you don't have to worry about touching any code to change the output.
Your class should ideally provide the data only. Use another PHP file or generic class to output HTML, so later you could output e.g. XML, JSON, etc from the same data class. This separates your data processing (model/controller) from your data representation (view).
I would disagree with using a template engine like Smarty. PHP is a template engine.
You can use output buffering. It's helping to build your templates and not be forced to process data in the display order.
<?php
$posts = take_data_from_class();
ob_start();
require_once('path/to/posts.php');
$html_posts = ob_get_clean();
// you can do the same with other parts like header or footer
ob_start();
require_once('path/to/header.php');
$header = ob_get_clean();
ob_start();
require_once('path/to/footer.php');
$footer = ob_get_clean();
?>
In posts.php you can display the posts:
<? foreach ($posts as $p) { ?>
<div class="...">
post data here
</div>
<? } ?>
Now, to display the whole thing:
<?php echo $header . $html_posts . $footer; ?>
More at http://us3.php.net/manual/en/book.outcontrol.php
Enjoy!
Im not familiar with Smarty at all...how exactly does that work, and what are the benefits of using a smarty vs. just creating functions to take large amounts of data and return html containing that data just to be echoed later?