Mixing ordered lists, links and variables in PHP/HTML - php

I'm taking a break from Project Euler to learn some PHP/HTML for kicks and giggles, and I found a page of simple exercises. So, on my 'site,' I want to have an ordered list of links to pages of each of the exercises, but I decided to do it in a dynamic manner as opposed to hard coding each item as I do the exercise. Unfortunately, the page that should contain the list doesn't render at all!
Assuming I have files on my system with the names "exawk#.php," what else could be wrong with this code? Sorry if it is sloppy or horrible, it's literally my first day of web programming.
<html>
<head>
<title> Awaken's Exercises </title>
</head>
<body>
<h1>This page contains "Awaken's Exercises" from
<a href="http://forums.digitalpoint.com/showthread.php?t=642480">
this page</a>.</h1>
<ol>
<?php
$arex = glob("exawk*.php"); // $arex contains
//an array of matching files
$numex = 0;
$i = 0;
foreach( $arex )
{
$numex++;
}
while( $numex >= 0 )
{
echo "<li><a href=" .$arex[$i].
">Problem #" .$numex. ".</a></li>";
$numex--;
$i++;
}
?>
</ol>
</body>
</html>

Enable display_errors in php.ini: foreach( $arex ) is a syntax error (missing .. as $varname).
From the commandline, you could check it with php -l /path/to/your/file.php.
Also, this sample:
//an array of matching files
$numex = 0;
foreach( $arex as $youdontdoanythingwiththis)
{
$numex++;
}
Could be:
$numex = count($arex);
Better the whole thing:
while( $numex >= 0 )
{ ...etc
Could be:
$num = 1;
foreach($arex as $file){
echo '<li>Problem #'.$num.'</li>';
$num++;
}

Related

(PHP) How do I properly concatenate a list of arrays into a string for file_put_contents?

I've been playing around with a php input function that will build a html page for a game, something like a wiki. All is going fine and dandy but when trying to build an array into a string it's passing back some funny errors.
It's happening to every one that involves an array and I've snipped some code out that works independently to save me time, but just can't figure it out. I'm using the Linux Terminal to run the script and when I set it to echo inside the foreach loop it does it just fine, it just won't when I try building it into a HTML file.
Here is the input script:
echo "\nHow many ranks were there (number)?:\n";
$facInputRankLimit = readline();
echo "Please read carefully and supply the ranks in descending order (HIGHEST > LOWEST):\n";
$facInputRankCount = 0;
$facInputRankString = "";
while ($facInputRankCount < $facInputRankLimit) {
echo "Enter a rank:\n";
$facInputRanks[$facInputRankCount] = readline();
$facInputRankCount++;
}
foreach ($facInputRanks as $facInputRankList) {
$facInputRankString .= $facInputRankList.PHP_EOL;
}
Then I'll build it into a multi-line echo (rather than appending every single block of code):
$facBuildPage = <<<EOT
<?php
\$facRankLimit = '$facInputRankLimit';
\$facRanks = '$facInputRankString';
include('faction2.html');
?>
EOT;
The variables with the backslashes will then be built into "$facFileName.php" and will be a set of variables inputted through this script (input2.php), which will each also include the same html page.
To top it off I'm getting really weird results... if I create 5 ranks, each as "1 2 3 4 5", I actually get "1 2 3" with two vertical linebreaks in between.
Edit: Snipped some of it, I didn't want to risk not adding enough info but it turns out I added a bit much.
For instance, the input I'm giving is:
$facInputRankLimit = 5;
$facInputRanks[1] = 1; -> $facInputRanks[5] = 5;
But it prints:
1<br><br>2<br><br>3
#Deepkak - The relative code in faction2.html is:
<div class="fpDivisions fpBox">
<span class="header">Ranks</span><br>
<?php
$facRankCount = 0;
while ($facRankCount < $facRankLimit) {
echo $facRanks[$facRankCount].'<br>';
$facRankCount++;
}
?>
</div>
I Hope this will solve the issue
<?php
echo "\nHow many ranks were there (number)?:\n";
$facInputRankLimit = readline();
echo "Please read carefully and supply the ranks in descending order (HIGHEST > LOWEST):\n";
$facInputRankCount = 0;
while ($facInputRankCount < $facInputRankLimit) {
echo "Enter a rank:\n";
$facInputRanks[$facInputRankCount] = readline();
$facInputRankCount++;
}
$array = [];
foreach ($facInputRanks as $facInputRankList) {
$array[] = "'".$facInputRankList."'";
}
$facInputRankString = "[".implode(",",$array)."]";
$facBuildPage = <<<EOT
<?php
\$facRankLimit = '$facInputRankLimit';
\$facRanks = $facInputRankString;
include('faction2.html');
?>
EOT;
echo $facBuildPage;
I've created a workaround for this, incase anyone needs any help in the future. It was as simple as echoing it from the HTML page, rather than creating a loop that runs through both the PHP script and the HTML code.
PHP input code:
echo "\nHow many ranks were there (number)?:\n";
$facInputRankLimit = readline();
echo "Please read carefully and supply the ranks in descending order (HIGHEST > LOWEST):\n";
$facInputRankCount = 0;
while ($facInputRankCount < $facInputRankLimit) {
echo "Enter a rank:\n";
$facInputRanks[$facInputRankCount] = readline();
$facInputRankCount++;
}
$facInputList = implode("<br>", $facInputRanks);
PHP output code:
$facBuildPage = <<<EOT
<?php
\$facRanks = '$facInputList';
include('faction2.html');
?>
EOT;
file_put_contents("test/$facFileName.php", $facBuildPage);
HTML output code:
<div class="fpDivisions fpBox">
<span class="header">Ranks</span><br>
<?php echo $facRanks; ?>
</div>

How to display banner after three post?

Below is the code to display the post. That loads every 10 posts. And I want to display banner after 3 post. Can someone tell me, code to display banner after 3 post? By completing the code below. Thank you so much for your help.
<?php
$stories = Wo_GetPosts(array('limit' => 10));
if (count($stories) <= 0) {
echo Wo_LoadPage('story/no-stories');
} else {
foreach ($stories as $wo['story']) {
echo Wo_LoadPage('story/content');
}
}
?>
You are trying to use count() in a way that this function is not intended. Per the PHP documentation:
Counts all elements in an array, or something in an object.
http://php.net/manual/en/function.count.php
What you need to do is create a counter variable that increments within your foreach loop, and when it hits 3 outputs the banner. Your code might look something like this:
<?php
$stories = Wo_GetPosts(array('limit' => 10));
// No stories; output error
if (count($stories) <= 0)
echo Wo_LoadPage('story/no-stories');
// Stories exist; show them!
} else {
$count = 0;
// Loop through $stories
foreach ($stories as $wo['story']) {
// Increment the value of $count by +1
$count++;
if ($count == 3) {
// Output my Banner here
}
echo Wo_LoadPage('story/content');
}
}
?>
One thing I would note is that the above code only outputs a banner one time; when the value of $count is 3. You could adjust this to run ever 3rd story by changing the match from if ($count ==3) to if ($count % 3 == 0) which essentially reads as If the value of $count is divisible by 3.
I guess you create some HTML Code with this? If true, I'd use some Javascript for this purpose. Something like this:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div id="stories">
<div>story 1</div>
<div>story 2</div>
<div>story 3</div>
<div>story 4</div>
</div>
<script type="text/javascript">
$("#stories>div:nth-child(3)").after('<div class="banner">your bannery</div> ');
</script>
</body>
</html>

Creating multiple divs according to variable

Removed (by original poster) due to unclear formulation of question.
More accurate question: Create divs associated to objects
for ($i = 0; $i < $amountOfPersons; $i++)
{
?>
<div class="fixed-size-square">
<span><?php echo $someContentThatBelongsToPerson[$i]; ?></span>
</div>
<?php
}
Assuming you'll get your database results returned to you in an array, the common way of doing this would be this in PHP:
foreach( $persons as $person ){
echo '<div class="fixed-size-square">
<span>I\'m a 200 x 200 px square with centered content no matter how many lines it takes</span>
</div>';
}
You could do it with the $amountPersons variable too (although I don't know why you'd want that if you get a result set back from the database), like this:
for ( $i = 0, $i < $amountPersons, $i++ ){
echo '<div class="fixed-size-square">
<span>I\'m a 200 x 200 px square with centered content no matter how many lines it takes</span>
</div>';
}
edit:
By the way, re-reading your question I realized you want to eventually put names in your divs, presumably the names stored in your database. You can do that with the first example, like this (this assumes the column name is your database is personName and that your result set is an array of objects.):
foreach( $persons as $person ){
echo '<div class="fixed-size-square">
<span>Name: '.$person->name.'</span>
</div>';
}
Since you have not tagged this as JavaScript, I can only assume you want a PHP approach to this, when you build the page I can only assume that you are running a query to get the records from the DB (since no code is provided).
All you need to do is wrap your div inside a for loop like this.
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<?php
for($i = 0; $i < $AmountPersons; $i++){
echo '
<div class="fixed-size-square">
<span>I\'m a 200 x 200 px square with centered content no matter how many lines it takes</span>
</div>
';
}
?>
</body>
</html>
Hope this helps!
Try this
for ($i = 0; $i < $amountOfPersons; $i++) { ?>
<div class="fixed-size-square">
<span><?php echo $someContentThatBelongsToPerson[$i]; ?></span>
</div>
<?php } ?>

php crumbtrail using file names

Im trying to create a crumb trail for a custom web script that drills down three levels into a link system. there are not many pages so my idea seem less work than to integrate someone else's script !
this is how i mark or identify the page in the header of each page
first level page
<?php $page = 'index_week'; ?>
second level page
<?php $page = 'index_week_list'; ?>
third level page which is also the details page and no deeper levels exist after this
<?php $page = 'index_week_ details'; ?>
My questions are...
1-how do i give each of these a label to that i can show them in the crumb trail and not show ""index_week_ details""
2-how do i link the file name to go back to a previous level with the identifier i used so that it picks up the listing id i used to filter that page's content form the database?
Below the header are and beginning of each page to see my dilemma !
the first lever page
<?php
include("inc_login_config.php");
include("inc_gen_constants.php");
include("inc_meta_header.php");
require("inc_dbsql.php");
include("inc_link_sql.php");
?>
<?php $page = 'index_week'; ?>
</head>
<body marginwidth="0" marginheight="0">
<!-- End of all general inclusuions -->
<?php
$db = new LinkSQL($dbname);
$homecataresult = $db->getchildcatalog(0);
$table="linkexcatalog";
mysql_connect ($dbhost,$dbuser,$dbpassword);
#mysql_select_db ($dbname);
$result = mysql_query("select catalogid,catalogname,parentid from $table where arentid='0' order by priority asc" );
$num_fields = mysql_num_fields($result);
$num_rows = mysql_num_rows($result);
$row_cnt = 0;
while ($num_rows>$row_cnt)
{
$record = #mysql_fetch_row($result);
?>
<?php print "$record[1]"; ?><br>
<?php $row_cnt++;} ?>
<?php mysql_close(); ?>
The other Two PHP files looks much the same except i have different LEVEL page id in them ?
I hope i don't confuse to much !
Ta any help appreciated.
Break up your string (into an array) on _'s, then loop on that array to create the breadcrumbs.
Here's a quick example:
<?php
$me = 'index_week_details';
//Break into an array
$parts = explode('_', $me);
//Debug
//print_r($parts);
//Create breadcrumbs
$path = '';
foreach($parts as $part) {
$path .= $part . '_';
echo '' . $part . '' . "\n";
}
You can play with it live here:
http://codepad.org/dFpujKZ8
Input:
index_week_details
Output:
index
week
details

if last element echo'class="last"'

I am new to php and I am trying to create a simple bit of code that prints a "last" class at the start of the last element in a "while" loop. There are only two items in the loop (blog excerpts) hence why I have tried below with the if ($i == 1)... Thanks for any help.
Here is my code so far - which only returns the p
<?php
$i = 0;
if($i == 1) {
echo '<p class="last">';
}
else {
echo '<p>';
}
?>
EDIT:
Thanks for the help so far. Greatly appreciated - I have provided a bit more information below (I posted late at night, so I realise I haven't been all that clear).
This is the full piece of code I am trying to write. It is pulling blog excerpts from Wordpress - currently limited to 2 blog articles.
<?php
$posts = new WP_Query('showposts=2');
while ( $posts->have_posts() ) : $posts->the_post();
?>
<p><?php echo the_title(); ?><br/>
<?php echo substr(get_the_excerpt(), 0,200); ?>... Read More</p>
<?php endwhile; ?>
<?php wp_reset_query(); ?>
I am wanting to add the class "last" to the p at the start of line 5 - for the last blog except only.
Thanks again.
Nick's answer says almost all that needs to be said.
The only thing I might add is a slight variation to save duplication particularly if the the contents of your paragraph tags is more complicated.
This might be better done with the following tweak on Nick's code:
<style>
#contents p:last-child {
PUT CONTENTS OF CLASS HERE
}
</style>
<body>
<div id="#contents">
<?php
$numLoops = 2;
$ctext=""
for($i=0; $i<$numLoops; $i++) {
$info="whatever";
if($i == (numLoops-1)) {
$ctext=' class="last"';
}
echo "<p${ctext}>${info}</p>\n";
}
?>
</div>
</body>
Cheers
So you have two paragraphs, and you want to apply the class "last" to the last one? Sounds like this is better handled with CSS
<style>
#contents p:last-child {
PUT CONTENTS OF CLASS HERE
}
</style>
<body>
<div id="#contents">
<p> first info</p>
<p> last info </p>
</div>
</body>
OR if you want to learn about loops
<?php
$numLoops = 2;
for($i=0; $i<$numLoops; $i++) {
if($i == (numLoops-1)) {
echo '<p class="last">';
} else {
echo '<p>';
}
}
What we are doing here with the for loop is initially setting the variable $i=0; then setting a test that says keep looping as long as the variable is less than the number of loops we want do do. Next we are setting what to do each loop, in this case we increment our variable by one each time.
First loop
i=0, we see that 0 is < 2 so we continue
Second loop
We execute the $i++ so we increment $i by 1 from 0 to $i=1,
we test and see $i=1 is still less than 2 so we continue.
Third attempted loop
We increment $i by 1 and get $i=2.
We test to see if this is less than 2, but it is NOT so we do not execute code in the loop
The main issue is that you don't have a loop in your code, and if you did you aren't incrementing your variable $i

Categories