Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations sizbut on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Splitting pages in one field 1

Status
Not open for further replies.

sinbadly

Technical User
Mar 16, 2006
126
GB
I want to add the choice of splitting pages to the field 'story'. I'm using $myrow['field']s and displaying them with the printf() function.

I can't work out where to put the spliti function. Should it go within printf() for the 'story' $myrow field?

Some advice from PHP people who know would be appreciated very much.

. . . . . . . <my code>

printf(" %s\n<br>",

// Split the text into an array of pages
$textarray = spliti('\[PAGEBREAK]', $result);
// Select the page we want
$result = $textarray[$page];
$PHP_SELF = $_SERVER['PHP_SELF'];
if ($page != 0) {
$prevpage = $page - 1;
echo "<p><a href=\"$PHP_SELF?id=$id&amp;page=$prevpage\">".
'Previous Page</a></p>';
}
echo "<p>$b</p>";
if ($page < count($textarray) - 1) {
$nextpage = $page + 1;
echo "<p><a href=\"$PHP_SELF?id=$id&amp;page=$nextpage\">".
'Next Page</a></p>';
}
$myrow["story"]);
. . . . . .

You can probably see that it doesn't work this way. Help, please, Masters.
 
i'm not sure i'd approach it in quite the same way. here is an alternative that closely resembles your code. hopefully it is self-explanatory:

Code:
<?
// Split the text into an array of pages
//assume the whole story is stored in the $row['mystory'] array element
if (!isset($_GET['id'])):
	die ("No story id supplied");
else:
	$id = (int) trim($_GET['id']);
endif;
$id = $result = mysql_query("Select mystory from stories where id = '$id'");
$row = mysql_fetch_assoc ($result);

$textarray = explode("\[PAGEBREAK]", $row['mystory']);
$page = isset($_GET['page']) ? (int) trim($_GET['page']) : 0;

if ($page != 0) {
  $prevpage = $page - 1;
  echo "<p><a href=\"".$_SERVER['PHP_SELF']. "?id=$id&amp;page=$prevpage\">".
	  'Previous Page</a></p>';
}
echo "<p>$b</p>";
				if ($page < count($textarray) - 1) {
  $nextpage = $page + 1;
  echo "<p><a href=\"".$_SERVER['PHP_SELF']. "?id=$id&amp;page=$nextpage\">".
	  'Next Page</a></p>';
}    
		
?>
<!-- now put the story in -->
<? if (!empty($textarray[$page])): ?>
<div class="story" style="background-color:#FFFDD9; color:#7330FE; font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10px; width:80px; margin:0 auto; border:1px solid #CC99CC; text-align:left">
<?=$textarray[$page]?>
</div>
<? endif; ?>
 
jpadie
Good to hear from you. This looks really good, I must say. Thank you very much. I'm going to work with it now ... will report back. Cheers
 
jpadie -
Merging yours with my coding, or attempting to, I arrive with the following. But somehow, it isn't displaying the field 'story'.

I'm showing you this - I hope you won't mind - so you can see all of the fields involved.

if( isset($_GET['id']))
{
$id = $_GET['id'];
$result = mysql_query("SELECT
sub,
head,
pix,
intro,
story,
byline,
link,
DATE_FORMAT(updated, '%d/%m/%y %H%i') as ud
FROM connex
WHERE id=$id
");
$myrow = mysql_fetch_assoc($result);

if ($myrow["sub"]) printf("<div class=\"Subheads\">%s\n</div>", $myrow["sub"]);
if ($myrow["intro"]) printf("<div class=\"intro\">%s\n</div>", $myrow["intro"]);
if ($myrow["head"]) printf("<h1>%s\n</h1>", $myrow["head"]);
if ($myrow["pix"]) printf("<img src=\"images %s", $myrow["pix"]);
//printf(" %s\n<br>",
//$id = $result = mysql_query("Select story from stories where id = '$id'");
//$row = mysql_fetch_assoc ($result);
$textarray = explode("\[PAGEBREAK]", $row['story']);
$page = isset($_GET['page']) ? (int) trim($_GET['page']) : 0;
if ($page != 0) {
$prevpage = $page - 1;
echo "<p><a href=\"".$_SERVER['PHP_SELF']. "?id=$id&amp;page=$prevpage\">".
'Previous Page</a></p>';
}
echo "<p>$b</p>";
if ($page < count($textarray) - 1) {
$nextpage = $page + 1;
echo "<p><a href=\"".$_SERVER['PHP_SELF']. "?id=$id&amp;page=$nextpage\">".
'Next Page</a></p>';
}
?>
<!-- now put the story in -->
<? if (!empty($textarray[$page])): ?>
<div class="story" style="background-color:#FFFDD9; color:#7330FE; font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10px; width:80px; margin:0 auto; border:1px solid #CC99CC; text-align:left">
<?=$textarray[$page]?>
</div>
<? endif;
if ($myrow["byline"]) printf("<div class=\"names2\">- %s</div>", $myrow["byline"]);
echo '<p> You can download the <em>Next Steps</em> booklet in pdf format <a href="../careers/NextSteps.pdf" target="_blank"title="Download the Next Steps booklet in PDF format.">here</a>, or as a Word document <a href="../careers/NextSteps.doc" target="_blank" title="You can download the Next Steps booklet in Word format here.">here</a>. </p>';
printf("<div id=\"date2\"> Updated: %s</div><p>",$myrow["ud"]);
//10/3/06 = = = = = I N C L U D E S F O R L I N K S
echo '<p></p>';
//include "contact_expert.inc.php";
if ($_GET['id'] > 2)
include "work_chances.inc.php";
//include "who_is_ch.inc.php";
}
else
{
//show list
$result = mysql_query("SELECT
head,
blurb,
id,
updated
FROM connex
ORDER BY id");
if ($myrow = mysql_fetch_assoc($result))
{
do {
// the List
printf("<h1 class=\"small\">%s</h1>
%s\n<br>
<span class=\"aim\"><a href=\"%s?id=%s\" title=\"Link to the story.\">
Article %s &nbsp;&gt;&gt;</a>
</span> <br>
<div id=\"date2\"> %s</div><br>
<hr align=\"left\" color=\"#FFFFFF\" width=\"250\" size=\"1\"><br>\n",
$myrow["head"],
$myrow["blurb"],
$PHP_SELF,$myrow["id"],
$myrow["id"],
date("D j/m/y", strtotime($myrow["updated"])));
} while ($myrow = mysql_fetch_assoc($result));
} else {
echo "Sorry, bulletins not found. Please try again later.";
}
}
?>
 
for starters you will need to change this line:
Code:
$textarray = explode("\[PAGEBREAK]", $row['story']);

to
Code:
$textarray = explode("\[PAGEBREAK]", $myrow['story']);

post back the result of this change before we check on other possible errors.
 
Sorry about that, jpadie. I've corrected that and now I get a good display of the text in 'story'.

It doesn't split the story into sections though. Be very grateful if you wouldn't mind pointing out what I might have done wrong there, please.
 
can you post a "story" in the forum? or if it is too long please email it to me at my handle AT hotmail.com

i suspect the problem is in the exploding and the pagebreak characters. i'm around for an hour or so.

Justin
 
Hi Justin

The story follows. Thanks very much for your expertise, or/and expert-eyes.

You don't think the coding line with the '?' in it isn't a problem? - It's just that it's new to me. (Well, almost everything is.) This one -

$page = isset($_GET['page']) ? (int) trim($_GET['page']) : 0;

<!-- <p> LMI </p>
<p>The construction industry </p>
<p>The national picture </p>
<p>The London angle</p>
<p> Recruitment</p>-->



<p><strong>The national picture</strong>:
About 2 million people or 1 in 14 of the UK workforce, are employed in construction. 46% are qualified to NVQ3 or above and 41% completed some form of apprenticeship. </p>
<p>A 2003 report by the CITB found that relatively few employers were unhappy about the skill levels of most of their existing workforce but that there was concern about the skills of new employees. </p>
<div id="RightQuote">
<img src="../images/xtras/GreyQuote.gif"> The trend in applications is now up again and the CITB has set up a scholarship scheme to encourage able young people to apply to HE courses relevant to the industry - <a href=" here</a> for details.The closing date for applications is May 30. <img src="../images/xtras/GreyUnquote.gif">
</div><p>
Interestingly, employers' reports of skill gaps are fewer in construction than for the rest of the economy. Nearly half of all construction work is repair and maintenance work with private commercial work the second largest part of the industry.
</p>

<p>
<a href=" Construction Industry Training Board</a> [CITB] predicts modest growth [about 2%] in employment in the industry. In the short term employment in all occupations is expected to grow except for plasterers and clerical staff. </p>
<p>In the longer term, by the end of the decade, the CITB expects that the industry will need fewer craft personnel but more managers, technicians, sales and customer service personnel. </p>
<p>
A worrying trend for the industry was a spectacular decline in the numbers of applicants for construction courses in higher education with a number of courses closing through lack of numbers.
</p>
[PAGEBREAK]
<p>
The trend in applications is now up again and the CITB has set up a scholarship scheme to encourage able young people to apply to HE courses relevant to the industry - <a href=" here</a> for details. The closing date for applications is 30/5/06.
</p>
<p>
The majority of construction firms are small. 47% of companies in the industry are sole traders, less than 10% employ more than 50 staff and less than 1% employ over 250. </p>
<p>These large companies [250+ staff] though account for approx. 30% of direct employment and 36% of output. About 35% of those working in the industry are self-employed and this proportion is over 50 % for many trades, such as plastering, painting and decorating, bricklaying, roofing and carpentry. </p>
<p>
It remains a largely male and white industry. 9.3% of the workforce is female and 2.4% comes from ethnic minorities, though there is a marked increase in the latter amongst new trainees. In terms of numbers the most common occupations are in descending order: wood trades, managers, electricians, office staff, plumbers and bricklayers. [PAGEBREAK] </p>
<p>Generally it is an aging workforce with a decline in recent years in the numbers of people under 30 employed in the industry and rising numbers over 40. </p>
<p>
Among those employers who do recruit 16-24 year olds the most common ways of recruiting were advertising in the local or regional press or word of mouth. The most common factors looked for are interest, enthusiasm and willingness to learn. [PAGEBREAK]
</p><p>
<strong>Technological change</strong>: Since so much of the industry is involved in the maintenance and repair of existing buildings change is gradual. </p>
<p>The increasing use of timber frames is likely to lead to some increase in employment in the wood trades
and the increasing use of IT in buildings will result in a higher demand for electricians to carry out its installation and maintenance. Prefabrication off site, already common in the industry, is likely to increase. </p>
<p>
On site work is likely to become increasingly likely to become an assembly process of factory-produced products. In the long term it is expected that this will lead to fewer tradespeople working on site and put a premium on staff with planning and logistics skills. [PAGEBREAK]
</p>
<h1 class="guard">The local picture</h1><p>
In London, 200,000 are employed in the industry of London?s workforce. The number peaked at nearly 300,000 in the late 1980s, fell sharply in the early 1990s and since has remained fairly stable. </p>
<p>About 60% of London?s construction activity is new build, higher than the national average, and private commercial work, largely offices, is the most significant part of it.
</p>
<p>
The remainder is in repairs and maintenance. As one might expect, large firms [115+ staff] carry out over half the new work with smaller firms tending to concentrate on the repair and maintenance sector. </p>
<p>The industry in London is more volatile than the rest of the country and its state is influenced by the state of the property market and the relative performance of non-property investments. </p>
<p>
Construction employment fell faster in London in the early 1990s but then recovered more quickly. </p>
<p>[PAGEBREAK] </p>
<p>
In such a mobile industry as construction there are few meaningful figures just for East London. In fact, the industry? characteristics of small business, self employment, contracting, sub contracting and cash payment make most statistics unreliable. </p>
<p>It is common for someone, say, to live in East London, work for a firm based in West London work on contracts mainly in Central London. </p>
<p>
About a quarter of construction jobs are filled by commuters living outside London. In London overall construction has now returned to the levels of the early 1990s. Only modest further employment growth is expected in the industry. </p>
<p>Though the value of construction work in London has gone up, increasing productivity has not led to an increase in the workforce. </p>
<p>[PAGEBREAK] </p>
<p>
A smaller proportion of construction employers in London report vacancies and skill shortages than construction employers nationally and they are no more likely to report skill shortages than London employers as a whole.
</p>
<p>
The age profile is broadly similar to the national one. 10% are female and 13% come from black and ethnic minority groups. Interestingly, given the publicity given to the influx of workers from Eastern Europe, the proportion of workforce born overseas at 20% is lower than the London average for all sectors of 27%. </p>
<p>The largest occupational groups in descending order are <ul>
<li class="ListCube">managers, </li>
<li class="ListCube">wood trades, </li>
<li class="ListCube">electricians, </li>
<li class="ListCube">plumbers and </li>
<li class="ListCube">professionals.</li></ul> </p>
[PAGEBREAK]
<p>
As regards skill shortages employers report the skills in shortest supply are carpenters and joiners, bricklayers and painters and decorators. </p>
<p>In the last few years there has been considerable rise in first year intake into the industry though the proportion of apprentices is below the national average. One problem in London is the lack of specialist training provision. </p>
<p>Courses in areas such as shopfitting, plant operation and steel fixing are only available outside the London area. The proportion of first year trainees in the industry taking a Modern Apprenticeship is well below the national average. </p>
<p>
Forecasters differ in their projections of construction employment and the lack of reliable statistics make projections difficult.</p>
<p> Oxford Economic Forecasting are the most optimistic, predicting a rise to approx. 250,000 by 2015 and GLA Economics the most pessimistic, predicting a decline to about 150,000. </p>
<p>Other forecasters estimates are between these extremes and the general consensus is that employment will remain broadly stable at around the 200,000 mark. </p>
[PAGEBREAK]
<h1 class="guard">Recruitment</h1>
<p>
The<a href=" Employment Service</a>has plenty of vacancies in the industry but they are mostly for skilled and experienced staff. </p>
<p>The CITB tries to place into work those under 25 who pass its aptitude test but they cannot guarantee to and advise people to make their own direct approach to employers. They are ?not an employment agency? in the words of one of its Training Advisers. </p>
<p>They also advise would be entrants to the industry to apply for full time courses as a back up. </p>
<p>
There would seem to be a paradox of a reported labour shortage but few advertised vacancies for new entrants. In fact, labour shortages in the industry are no worse than for other industries in London and are lower than in the UK as a whole.
</p><p>
One other explanation for the lack of advertised vacancies is that much recruitment in the industry is by direct approach and word of mouth. It is normal practice for people to approach the site agent on a building site to see if there is any work. [PAGEBREAK]
</p>
<p>
Staff who do a good job on one site are then invited back to work on others. In London there is the additional factor that many construction workers are 'commuters' from other parts of the country so the vacancies, if advertised, are elsewhere. </p>
<p>The best advice we can give to those who seek our help is to send off speculative applications to likely employers and to help them build up lists of local firms. </p>
<p>
Another explanation is the structure of the industry is highly fragmented with mostly small firms and 43% of construction workers in London being self-employed. Despite the best efforts of the CITB few firms are in a position to offer structured training. </p>
<p>A 2003 CITB report says, 'Construction work is almost entirely done on a project by project basis, whereby contractors will draw together teams of people who often work for quite a short period of time and then move on to another location or disperse. </p>
<p>'Much of this work is managed by a main contractor who deals with client but who sub contracts parts of it to smaller firms who specialise in particular aspects of the process. </p>
<p>[PAGEBREAK] The CITB report goes on,
'To cope with fluctuating workload, much of the workforce at site level is hired on a self-employed basis. In this form of <em>secondary </em>labour there is little opportunity or incentive to invest in training. </p>
<p>'Research into companies who rely heavily on self employment show them to be the least involved in training,' the report states. </p>
<p>
<strong>Older applicants:</strong> There is no particular upper age limit but much of the financial support for trainees is for under 25s. In practice there seems to be little recruitment of new entrants over 50 into the industry.
</p>


<p class="indent"><font color="#FF9933"><b>Main sources</b></font>: CITB research reports, GLA Economics. I am building up a file on the industry at SOV which staff are welcome to consult. Please contact me on 020 8536 3647 or you can <a href="mailto:charles.harvey@vtplc.com">email me</a>.
</p><p>
<p class="indent"><font color="#FF9933"><b>Recommended reading: </b></font><br>
<a href=" the foundations</a> - London's construction industry (GLA Economics February 2006).
<p class="indent"><font color="#FF9933"><b>Links</b></font>:<br>
<a href=" Employment Service</a><br>
<a href=" relevant courses</a><br>
<a href=" Construction Industry Training Board</a><br>
<a href="mailto:charles.harvey@vtplc.com" title="You can email Mr Harvey from here.">Contact the expert</a></p>
 
nope (at least not yet). i think the line
Code:
$textarray = explode("\[PAGEBREAK]", $row['story']);
is the problem. i took the hint from your first code but in fact you are using just "[PAGEBREAK]" as your break tag.

so ... change the above line to
Code:
$textarray = explode("[PAGEBREAK]", $row['story']);
and let's see what happens next!
 
B R I L L I A N T !!!! Justin. That's it exactly. That is wonderful. Thanks so very much. I've spent hours and hours on it, because I would like to make it the general rule on this high school website.

Just a few words on a webpage must make it much more interesting to read. A whole blur of text, and I'm sure their minds will turn off right away.

Really very pleased, and very grateful. Thank you!
 
to explain

Code:
$page = isset($_GET['page']) ? (int) trim($_GET['page']) : 0;

this is a use of the ternary operator. see for the official note on it.

basically it is {expression ? TRUE : FALSE} so the code about could equally be written:
Code:
if (isset($_GET['page'])):
  $page = (int) trim($_GET['page']); 
else:
  $page = 0;
endif;

the trim function just cuts white space and other useless but potentially damaging characters from the front and back of the variable. the (int) casts the result to an integer (note that if you are using varchars or alphanumerics as the id field then the (int) casting will screw things up. if, as is suspect, you are using a numeric autoincrementer you should not have a problem. these are good tips to avoid sql injection.

hth
Justin
 
You receive just one vote for that, but I did try to give you one for each response. Well, please know that you deserve more. All the best
paul
 
Thanks. Yes, I use tinyint(3) for the id - well, all the ids throughout the database and website. (I run it like a news-site, so it is busy with 'stories'.)

Thanks very much for the advice. Printing it off and putting it into my php and mysql notebooks.

Cheers, Justin. I'll be incorporating your code into other pages over the weekend. Very much obliged.
 
great pleasure.

even cooler than a straight forward paging mechanism is if you coupled it with ajax.

download the saja.php library from
unzip the library in the same directory as the script and then replace the code that we worked on above with this code.

i have not been able to test the code without your database and data so apologies if there are errors. the net effect should be that the text will change without page refreshes being necessary. the code will also degrade ok if browsers do not support javascript or the user has turned js off.

please post back to let me know how this code works out.

Justin

Code:
<?
$textarray = array();

function getrow($id){
	if (!empty($id)):
		$result = mysql_query("SELECT 
						sub,
						head,
						pix, 
						intro,
						story,
						byline,
						link,
						DATE_FORMAT(updated, '%d/%m/%y %H%i') as ud
						FROM connex
						WHERE id=$id
								");
		return mysql_fetch_assoc($result);
	else:
		return false;
	endif;
}

function getpage($id, $page=0) {
	global $myrow;
	$contents = "";
	if (empty($myrow)):
		$myrow = getrow($id);
	endif;
	
	$textarray = explode("[PAGEBREAK]", $myrow['story']);
	$pagecontents = $textarray[$page];
	$pageref = $_SERVER['PHP_SELF'];
	if ($page != 0):
		$prevpage = $page - 1;
		$contents .= "
		<p>
		<a 
		onclick=\"getcontents('".$id."','".$prevpage."'); return false;\" 
		href=\"{$pageref}?id=$id&page=$prevpage\">
		Previous Page
		</a>
		</p>";
    else:
		echo "<p>&nbsp;</p>";
	endif;	
	if ($page < count($textarray) - 1):
		$nextpage = $page + 1;
		$contents .= "
		<p>
		<a 
		onclick=\"getcontents('".$id."','".$nextpage."'); return false;\" 
		href=\"{$pageref}?id=$id&page=$nextpage\">
		Previous Page
		</a>
		</p>";
	endif;

//this is heredoc syntax	
	$contents .= 
<<<CONTENTS
<div class="story" style="background-color:#FFFDD9; color:#7330FE; font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10px; width:80px; margin:0 auto; border:1px solid #CC99CC; text-align:left">
{PAGECONTENTS}
</div>
CONTENTS;
return str_replace("{PAGECONTENTS}", $pagecontents, $contents);
}

if( isset($_GET['id']))  
                {
                $id = $_GET['id'];
				$myrow = getrow($id);     
                if (($myrow =getrow($id)) == FALSE):
					die (mysql_error());
				endif;                
                if ($myrow["sub"])    printf("<div class=\"Subheads\">%s\n</div>", $myrow["sub"]); 
                if ($myrow["intro"]) printf("<div class=\"intro\">%s\n</div>", $myrow["intro"]);
                if ($myrow["head"])    printf("<h1>%s\n</h1>", $myrow["head"]);
                if ($myrow["pix"])  printf("<img src=\"images  %s", $myrow["pix"]);                       
                            //printf(" %s\n<br>", 
                         //$id = $result = mysql_query("Select story from stories where id = '$id'");
                        //$row = mysql_fetch_assoc ($result);
                $textarray = explode("[PAGEBREAK]", $myrow['story']);
                $page = isset($_GET['page']) ? (int) trim($_GET['page']) : 0;
				//new sajax code
				require_once "sajax.php";
				sajax_init();
				sajax_export("getpage"); // list of functions to export
				sajax_handle_client_request(); // serve client instances

				sajax_show_javascript();
?>
<script type="text/javascript">
function getcontents ($id, $page) {
	x_getpage($id, $page, setcontents);
}
function setcontents ($contents) {
	document.getElementById("contents").InnerHtml = $contents;
}

</script>
<?

                $contents = getpage ($id, $page); 
				echo "<div id=\"contents\">";
				echo $contents;                
				echo "</div>";
                if ($myrow["byline"])  printf("<div class=\"names2\">-  %s</div>", $myrow["byline"]); 
                            echo '<p> You can download the <em>Next Steps</em> booklet in pdf format <a href="../careers/NextSteps.pdf" target="_blank"title="Download the Next Steps booklet in PDF format.">here</a>, or as a Word document  <a href="../careers/NextSteps.doc" target="_blank" title="You can download the Next Steps booklet in Word format here.">here</a>. </p>'; 
                    printf("<div id=\"date2\"> Updated: %s</div><p>",$myrow["ud"]);
                    //10/3/06  = = = = =    I N C L U D E S  F O R  L I N K S 
                    echo '<p></p>';
                    //include "contact_expert.inc.php";
                    if ($_GET['id'] > 2)
                    include "work_chances.inc.php";
                    //include "who_is_ch.inc.php";
                }
                 else 
                {
                //show  list
                $result = mysql_query("SELECT 
                                            head, 
                                            blurb,
                                            id,
                                            updated
                                            FROM connex
                                            ORDER BY id");
                if ($myrow = mysql_fetch_assoc($result)) 
                {
                do {
                // the List 
                printf("<h1 class=\"small\">%s</h1>
                     %s\n<br> 
                    <span class=\"aim\"><a href=\"%s?id=%s\" title=\"Link to the story.\">
                    Article  %s &nbsp;&gt;&gt;</a> 
                    </span> <br>
                    <div id=\"date2\"> %s</div><br>
                    <hr align=\"left\" color=\"#FFFFFF\" width=\"250\" size=\"1\"><br>\n",
                    $myrow["head"], 
                    $myrow["blurb"], 
                    $PHP_SELF,$myrow["id"],
                    $myrow["id"],
                    date("D j/m/y", strtotime($myrow["updated"])));
                } while ($myrow = mysql_fetch_assoc($result));
                } else {
                echo "Sorry, bulletins not found. Please try again later.";
                }
                }
            ?>
 
Many thanks for this, Justin. Will get busy today with it, or over the weekend.

The main problem with the previous (non-saja) script.

1. With each following page, all the fields (called up in the select query) are present from page to page. What's desired, are the chosen paragraphs from 'story' on their own - nothing else.

I can get around this by putting all the fields into 'story', but this is no real answer because eventually it wants to be an automatic process. If 'story' > so_many_words, use pagebreaks etc.

Many thanks for your considerable help.
paul

Justin, is there a way to tell the other fields not to appear in the 'pagebreak' following pages. To appear only on the first page, please?
 
Hi Paul

not sure i fully grab the issue you're raising. are you concerned about server overhead on the db?

is there a link to your site that you can post to allow me to see the issue? [if you don't want the publicise the link feel free to email me at the address given in the post above]

Justin
 
Career pages on the site is where I'd most like to divie the articles. Only id=1 qualifies because I haven't posted the article I'm trying to pagebreak yet - because it's especially long, for kids.

Ideally, the visitor clicks on the id, and the first page of the article appears. Everything is there - heading, byline, includes etc etc, but just a few sentences.

He clicks on 'next' and ONLY the chosen piece of text appears - 4 or 5 sentences, perhaps. The same applies on the next page, if there is a next page.

If I could get it to work right, it'd be perfect to have throughout the site, wherever the report is over a certain length.

 
aha I understand. this is straightforward to fix.

i'll post back in a few minutes. the code may be fairly radically altered in structure but not in substance...
 
oops. bit more than a few minutes. sorry.

the code below is fully integrated with sajax. to turn on the functionality all you need to do is add a url parameter of "sajax=true". you do not need to use sajax tho. if you omit the parameter the page will work as normal.

big health warning: the sajax file is "included" from the sajax web site. this is a major security risk so you should ideally download the file and put it on your own server instead (and then change the include line).

second warning: i don't have your db structure or data to test this code. there are no syntax errors but that doesn't mean it will work off the bat. please post back.

enjoy
Justin
Code:
<?
if (isset ($_GET['sajax']))://new sajax code
	require_once "[URL unfurl="true"]http://absinth.modernmethod.com/sajax/sajax-0.12/php/Sajax.php.txt";[/URL]
	sajax_init();
	sajax_export("getpage"); // list of functions to export
	sajax_handle_client_request(); // serve client instances
endif;
?>
<?
$contents = "";
$myrow = array();

//MAIN DISPATCH SWITCHBOARD
$id = isset($_GET['id']) ? (int) trim($_GET['id']) :"";


//this is created as a switch in that you may consider using this method more widely and attaching an "action" directive to your query string.
switch ($id):
	case "":
		listarticles();
		break;
	default:
		getpage ($id);
		break;
endswitch;
//END OF MAIN SWITCHBOARD

function listarticles()
{
	global $contents;
	//show  list
	$result = mysql_query("SELECT
								head,
								blurb,
								id,
								updated
								FROM connex
								ORDER BY id");
	if ($myrow = mysql_fetch_assoc($result))
	{
		do {
	// the List
			$date = date("D j/m/y", strtotime($myrow["updated"]));
			$contents .= <<<CONTENT
	<h1 class="small">{$myrow["head"]}</h1>
	{$myrow["blurb"]}<br/>
	<span class="aim">
		<a 	href="{$pageref}?id={$myrow["id"]}" 
			title="Link to the story.">
		Article {$myrow["id"]} &nbsp;&gt;&gt;</a>
		</span> <br>
		<div id="date2">$date</div><br>
		<hr align="left" color="#FFFFFF" width="250" size="1"><br/>
CONTENT;
	
		} while ($myrow = mysql_fetch_assoc($result));
	} else {
	$contents .= "Sorry, bulletins not found. Please try again later.";
	}
}

function getfooter() {
global $myrow; 
return <<<FOOTER
<p> 
You can download the <em>Next Steps</em> booklet in pdf format <a href="../careers/NextSteps.pdf" target="_blank"title="Download the Next Steps booklet in PDF format.">here</a>, or as a Word document  <a href="../careers/NextSteps.doc" target="_blank" title="You can download the Next Steps booklet in Word format here.">here</a>. 
</p>
<div id="date2"> Updated: {$myrow["ud"]}</div>
<p> &nbsp; </p>
FOOTER;
}

function getfulldetails($id){
	//THIS FUNCTION RETURNS EVERYTHING YOU NEED TO BUILD THE FIRST PAGE OF EACH STORY
	if (!empty($id)):
		if(($result = mysql_query("SELECT
						sub,
						head,
						pix,
						intro,
						story,
						byline,
						link,
						DATE_FORMAT(updated, '%d/%m/%y %H%i') as ud
						FROM connex
						WHERE id=$id
								")) === false) return false;
		return mysql_fetch_assoc($result);
	else:
		return false;
	endif;
}
function getstory($id) {
	//THIS FUNCTION JUST RETURNS THE STORY AND IS USED FOR SUBSEQUENT PAGES
	if (!empty($id)):
		if(($result = mysql_query("SELECT
						story,
						DATE_FORMAT(updated, '%d/%m/%y %H%i') as ud
						FROM connex
						WHERE id=$id
								")) === false) return false;

		return mysql_fetch_assoc($result);
	else:
		return false;
	endif;
}

function chunkstory( $story, $page) {
	//static function.  this returns just the text of the relevant page
	$textarray = explode("[PAGEBREAK]", $story);
	return array("text"=>$textarray[$page], "count"=>count($textarray));
}

function getpage($id, $page=0) {
	
	global $contents ;
	global $myrow ;
	
	$sajaxinc = isset($_GET['sajax']) ? "&sajax=true" : ""; //used for sajaxing the link
	
	$contents = "";		//global container for the rendering
	$story =""; 		// container for the story page
	$pagelinks = "";		//container for page links
	$pageref = $_SERVER['PHP_SELF'];
	
	
	//this code decides whether to get the page and bylines or just the story
	if ($page>0):
		if (($myrow = getstory($id)) == FALSE):
			die (mysql_error());
		endif;
		
		$story = chunkstory($myrow['story'], $page);
		$prevpage = $page - 1;
		$pagelinks .= "
		<p>
		<a
		onclick=\"getcontents('".$id."','".$prevpage."');\"
		href=\"{$pageref}?id=$id&page=$prevpage{$sajaxinc}\">
		Previous Page
		</a>
		</p>";
		if ($page < $story['count'] - 1):
			$nextpage = $page + 1;
			$pagelinks .= "
			<p>
			<a
			onclick=\"getcontents('".$id."','".$nextpage."'); \"
			href=\"{$pageref}?id=$id&page=$nextpage{$sajaxinc}\">
			Previous Page
			</a>
			</p>";
		endif;
		$contents .= $pagelinks;
		$contents .=
<<<CONTENTS
<div class="story" style="background-color:#FFFDD9; color:#7330FE; font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10px; width:80px; margin:0 auto; border:1px solid #CC99CC; text-align:left">
{$story['text']}
</div>
CONTENTS;
		
	else:
		if (($myrow = getfulldetails($id)) == FALSE):
			die (mysql_error());
		endif;
		
		$story = chunkstory($myrow['story'], $page); 	//gets the story page
		$pagelinks .= "<p>&nbsp;</p>";
		
		if ($page < $story['count'] - 1):
			$nextpage = $page + 1;
			$pagelinks .= "
			<p>
			<a
			onclick=\"getcontents('".$id."','".$nextpage."'); \"
			href=\"{$pageref}?id=$id&page=$nextpage\">
			Previous Page
			</a>
			</p>";
		endif;
		
		$contents .= $pagelinks;
		$contents .= <<<CONTENTS
<div class="Subheads">
{$myrow['sub']}
</div>
<div class="intro">
{$myrow['intro']}
</div>
<h1>
{$myrow['head']}
</h1>
<img src="images/{$myrow['pix']}" />
<div class="story" style="background-color:#FFFDD9; color:#7330FE; font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10px; width:80px; margin:0 auto; border:1px solid #CC99CC; text-align:left">
{$story['text']}
</div>
<div class="names2">
{$myrow['byline']}
</div>
CONTENTS;
	endif;

	$contents .= getfooter();

	return $contents;
}
?>




<script type="text/javascript">
function getcontents ($id, $page) {
<? if (isset($_GET['sajax'])): ?>
x_getpage($id, $page, setcontents);
<? else: ?>
return true
<? endif; ?>
}
function setcontents ($contents) {
document.getElementById("container").InnerHtml = $contents;
}
<? if(isset ($_GET['sajax'])) {sajax_show_javascript();} ?>
</script>
<div id="container">
<?=$contents?>
</div><!--end of container div -->
 
Phew! Justin, this looks marvellous. Well, it's a hundred lightyears beyond my knowledge, but to a novice it looks amazing. Thanks very much. Can't wait to try it, though that probably won't be till tonight.

I couldn't get back on Friday to the site - Fridays are the busiest days. I don't have access over the weekends. However, my lateness is no indication of waning interest. I am really keen to get this right. It's what all newsy-type sites need, but more so for young people.

Very grateful, Master. Will report back soonest.

(Like the idea of going without sajax. Thank you. Perhaps it's because I'm newly using php, but it would be good to do it all with just php and mysql.)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top