PHP line break

Hi Guys,

Im using the following bit of code to display data from mysql database on my website. This is working really well and in the next few weeks I’ll start to add the html and css content. At the moment when you go to the home page there is no gap between each row of data. Ive tried to add echo “/n” below the read more row but this doesn’t do anything.

I read online the echo “/n” creates a break in the code and not the appearance of the content? If this is correct how do I add a line break that affects the appearance?

its probably easiest if you look at the website as it currently is and you will see what i mean easily.

[php]

<?php // Assuming you've already connected to your database: $result = mysql_query("SELECT * FROM banter ORDER BY P_Id DESC"); // Replace "table_name" with the name of your table. // And replace "row_primary" with the name of the column you marked as the primary key. while ($row = mysql_fetch_array($result)) { $count= mysql_query("SELECT count(*) AS 'n' FROM comments WHERE parent='$row[P_Id]'"); $result2=mysql_fetch_array($count); echo "
"; echo "
{$row['P_Id']}
"; // Replace "column_one" with the name of your first column. echo "
{$row['story']}
"; // Replace "column_two" with the name of your second column. echo "
$row[screen_name]
"; echo "
{$result2['n']}
"; // Replace "column_three" with the name of your third column. echo "
Read more
"; // Your submit button. (adds one to each row) echo ""; } mysql_close($con); ?>

[/php]

MAny thanks,

Sam

www.banterdonkey.com is the website… sorry!

Hi again,

You would add line breaks that would be used and displayed by a browser by inserting the
HTML tag in your HTML output in your PHP code.
will go from one line to another; but to have a space between lines just have two
. Don’t forget you can use \n, \r, and \t but it has to be in single quoted echos or else it won’t work.

Hope this helps.

Heya,

I understand what you are saying about the
but how do i insert these within <php?.. ?>

If i insert them outside the php tags it will just ad a line break at the bottom of the php content won’t it? not after each row of data?

Many thanks,

Sam

Hi again,

You would put the break tags inside of the echo statement. Look at these examples:

[php]echo “This is a line break.
”;
echo ‘This is another line break.
’;[/php]

[php]echo $variable."
";
echo $variable.’
’;[/php]

Hope this helps.

I’m afraid it’s the other way round - to use special characters such as these you must use full speech marks ("\n") not single quotes (’\n’).

Yeah, I hardly ever use those so I took a gamble on which quotes needed to be used. Thanks Smokey for clearifying.

Thanks guys!

I don’t want you guys to think i’m getting you to code my site for me. Everything you teach me I learn from and add more content before getting stuck again!

My home page at the moment loads every post within a particular table on mysql database. What I would now like to happen is for there to be a determined number of posts before it goes on to the next page. For example lets say i want 10 post to appear on index.php?page1 the next 10 on index.php?page2 etc. I think this is called a page split?

Is there an easy way to code for this?

Many thanks

Sam

Well I have an old function that I sometimes use - funnily enough I’m currently working on sprucing it up and making it a bit more flexible, and also creating a class-based version of it. The old one requires an array of data and works out what to display from that array according to the options set (each post would be an element of the array). This requires the full content to be loaded each time however (one of the things I am looking to improve) - if this is okay, see below. I’m afraid it’s not commented, but I’ve put an example of use below:

[php]/**

  • Trawls through the $data array and prints $perpage elements up to $pagelistmax, using the page number in $_GET[$get]

  • @param array $data An array containing the data to be paginated. Each element should contain 1 item/piece of data.

  • @param integer $perpage How many pieces of data to show per page.

  • @param integer $pagelistmax How many pages to show in the page navigation element.

  • @param string $prev What to show as the ‘previous page’ button.

  • @param string $next What to show as the ‘next page’ button.

  • @param string $pgsep What to use to separate the page numbers in the page navigation element.

  • @param string $get The get variable to use for page numbers.

  • @param array $ignoregets An array containing the names of get variables that you want to stay put before appending the page number get variable.

  • @return string Echos out the data paginated with the pagination options/navigation included.
    /
    function paginate($data,$perpage = 9,$pagelistmax = 5,$prev = “<”,$next = “>”,$pgsep = “,”,$get = “page”,$ignoregets = array())
    {
    if(is_array($data) && !empty($data))
    {
    $returndata = array();
    $maxpages = ceil(count($data)/$perpage);
    if($pagelistmax > $maxpages) $pagelistmax = $maxpages;
    $pagenum = (isset($_GET[$get])) ? $_GET[$get] : 1;
    if($pagenum > $maxpages || $pagenum < 1) $pagenum = 1;
    $min = $pagenum
    $perpage - $perpage;
    $max = $pagenum + $perpage;
    for($i = $min; isset($data[$i]) && $i < ($perpage * $pagenum); $i++)
    {
    $returndata[] = $data[$i];
    }

     if($pagelistmax % 2 == 0)
     {
     	$pagelistfirst = $pagenum - (($pagelistmax) / 2) + 1;
     	$pagelistlast = $pagenum + (($pagelistmax) / 2);
     }
     else
     {
     	$pagelistfirst = $pagenum - (($pagelistmax-1) / 2);
     	$pagelistlast = $pagenum + (($pagelistmax-1) / 2);
     }
     if($pagelistfirst < 1) $pagelistfirst = 1;
     if($pagelistfirst == 1) $pagelistlast = $pagelistmax;
     if($pagelistlast > $maxpages) $pagelistlast = $maxpages;
     if($pagelistlast == $maxpages) $pagelistfirst = $maxpages - ($pagelistmax-1);
     $pagelist = range($pagelistfirst,$pagelistlast);
    
     $get2 = "";
     foreach($_GET as $var => $val)
     {
     	if(trim($val) != "" && trim($var) != $get && !in_array(trim($var),$ignoregets))
     	{
     		$get2 .= trim($var)."=".trim($val)."&";
     	}
     }
     $get = $get2.$get;
     foreach($pagelist as $key => $num)
     {
     	$temp = "<a href=\"?".$get."=".$num."\" title=\"Go To Page ".$num."\">".$num."</a>";
     	if($num == $pagenum) $temp = "<span class=\"pnate_curr\" title=\"You Are Currently Viewing Page ".$num."\">".$num."</span>";
     	$pagelist[$key] = $temp;
     }
     $pagelist = implode($pgsep,$pagelist);
    
     $plist = "<p class=\"pnate_pagelist\"><span>Page: </span>".$pagelist."</p>";
     $pnum = "<p class=\"pnate_pofp\">Page: ".$pagenum." of ".$maxpages."</p>";
     $prv = ($pagenum > 1) ? "<a class=\"pnate_prev\" href=\"?".$get."=".($pagenum-1)."\" title=\"View Previous Page\">".$prev."</a>" : "<span class=\"pnate_prev disabled\" title=\"No Previous Pages Are Available\">".$prev."</span>";
     $nxt = ($pagenum < $maxpages) ? "<a class=\"pnate_next\" href=\"?".$get."=".($pagenum+1)."\" title=\"View Next Page\">".$next."</a>" : "<span class=\"pnate_next disabled\" title=\"No More Pages Are Available\">".$next."</span>";
    
     $pnate_list = "<div class=\"pnate_pageinfo\">";
     $pnate_list .= $prv.$plist.$nxt.$pnum;
     $pnate_list .= "</div>";
     
     return array($pnate_list,implode('',$returndata));
    

    }
    else if(!is_array($data))
    {
    echo $data;
    }
    else
    {
    //No data available
    }
    }

list($pagelist,$data) = paginate($numbers,3);
echo $pagelist;
echo $data;
echo $pagelist;
[/php]

Requires styling etc, but shouldn’t require major editing of the function (may be confusing though - i wrote this really quickly for one website, altered it every time I used it - bit of a mess!)

Hey Smokey, I love your function. Shoot me a PM once you get a class created for it. I could try to do it myself, but I’m jammed packed with things I got to take care of. Good function though.

Hi Guys,

Thank you very much for your help. Without sounding really stupid what do you mean by “class”. LAst night before I got your replies I found this…

[php]<?php
if (isset($_GET[“page”])) { $page = $_GET[“page”]; } else { $page=1; };
$start_from = ($page-1) * 20;
$sql = “SELECT * FROM students ORDER BY name ASC LIMIT $start_from, 20”;
$rs_result = mysql_query ($sql,$connection);
?>

<?php while ($row = mysql_fetch_assoc($rs_result)) { ?> <?php }; ?>
Name Phone
<? echo $row["Name"]; ?> <? echo $row["PhoneNumber"]; ?>
<?php $sql = "SELECT COUNT(Name) FROM students"; $rs_result = mysql_query($sql,$connection); $row = mysql_fetch_row($rs_result); $total_records = $row[0]; $total_pages = ceil($total_records / 20);

for ($i=1; $i<=$total_pages; $i++) {
echo “”.$i." ";
};
?>[/php]

I think I understand the format of this one a little more but Im assuming that because of that its probably more basic and not as good as yours. Can you guys enlighten me on the differences and which one you think I should try and incorporate with my page?

Many thanks,

Sam

Firstly, thank you OpzMaster. I shall indeed PM you with the new version when it is completed.

For a fully detailed explanation you can see it explained here: http://uk3.php.net/manual/en/language.oop5.basic.php
(It’s basically an advanced function - only it’s multiple variables and functions collaborated into one object/“class” and all are contained within that class and must be referenced from that class, unlike regular variable/function initialisation)

In the case of this one section of script, provided you aren’t going to want to change any attributes of the pagination, my function will not be of use and will simply bloat your code. However, for reference see below it’s advantages:

[ul][li]The $_GET variable can be changed in one place, and will work throughout the script without changing anything else - it can also be ignored entirely and it will default to ‘page’[/li]
[li]Unlike your example, it not only checks for the page number to be specified, but it also ensures that it is a valid page number that will actually show results, if not, it defaults to 1[/li]
[li]If you place the function in a globally included file, you can use it anywhere on the site with just a couple of lines (calling the function and outputting)[/li]
[li]If you use mod_rewrite, your $_GET variables can be protected and not re-written using the $ignoregets array. Meaning that the urls it creates leaves the $_GET variables specified in $ignoregets and only appends any left out, plus the ‘page’ variable[/li]
[li]You can customise the ‘previous’ and ‘next’ links at each call of the function (or leave blank for the defaults)[/li]
[li]You can specify how many page numbers to list (“2,3,4,5” or “3,4” or “1,2,3,4,5,6,7”) between your previous and next links.[/li]
[li]The amount of items shown per page is easily changed on each call of the function[/li][/ul]

The main downside is the fact that you need to feed it the full set of data on each page load - although this doesn’t matter for smaller sites/projects, large projects that will be pulling large amounts of data from databases etc will no doubt suffer performance issues. This will be addressed in the new version.

If you have any other questions, or want me to give some example uses just let me know.

Hi Smokey,

Thank you for your explanation. I trying to create a really basic forum. The home page displays the posts contained in a set table of my mysql database. At the moment theres only around 20 posts - all ones i have posted for testing different aspects of the database. However when I have finished the site I would be hoping to get a far greater number of posts.

My website is www.banterdonkey.com this will give you an idea of the type of data handling. Sorry about the lack of html and css at the moment - i know it makes it hard to distinguish what is what on the site.

This is the code i am currently using to grab the data from the table and display it the way it is seen on the homepage. My only aim here is to limit the number of posts to a set number (say 10 for example) before going onto another page. If you are able to advise on which code you felt was best to suite my needs that would be really helpful.

[php]

BanterDonkey | The Source of Guernsey Banter
Home
Submit
Register
Contact
<?php $con = mysql_connect("host","user","password"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("database") or die(mysql_error()); // Assuming you've already connected to your database: $result = mysql_query("SELECT * FROM banter ORDER BY P_Id DESC"); // Replace "table_name" with the name of your table. // And replace "row_primary" with the name of the column you marked as the primary key. while ($row = mysql_fetch_array($result)) { $count= mysql_query("SELECT count(*) AS 'n' FROM comments WHERE parent='$row[P_Id]'"); $result2=mysql_fetch_array($count); echo "
"; echo "
{$row['P_Id']}
"; // Replace "column_one" with the name of your first column. echo "
{$row['story']}
"; // Replace "column_two" with the name of your second column. echo "
"; echo "
{$row['date']}
"; // Replace "column_one" with the name of your first column. echo "
{$row['time']}
"; // Replace "column_one" with the name of your first column. echo "
{$result2['n']}
"; // Replace "column_three" with the name of your third column. echo "
Read more
"; // Your submit button. (adds one to each row) echo ""; echo "

"; } mysql_close($con); ?> [/php]

Many thanks,

Sam

Well, as this may end up being on multiple pages, and depending on the popularity and growth you may want to change options such as how many posts per page or how many pages appear in the list of pages etc - which would all be easiest with my function. As an example, I have written how you could change your current code accordingly (not tested as I don’t have your database, but it should work) - you’ll notice I’ve combined your 2 queries into one - this should work fine, but let me know if not.

[php] include ‘paginate.func.php’;
$sql = “SELECT
COUNT(c.) AS n
, b.

FROM
banter AS b
INNER JOIN
comments AS c
ON
c.parent = b.P_Id”;
$query = mysql_query($sql);
if(mysql_num_rows($query) > 0)
{
$posts = array();
$i = 0;
while(($row = mysql_fetch_assoc($query)) !== false)
{
$posts[$i] = “

”;
$posts[$i] = “
”.$row[‘P_Id’]."
"; // Replace “column_one” with the name of your first column.
$posts[$i] = “
”.$row[‘story’]."
"; // Replace “column_two” with the name of your second column.
$posts[$i] = “
<a href='user.php?userid=”.$row[‘screen_name’]."’>".$row[‘screen_name’].“donkey
”;
$posts[$i] = “
”.$row[‘date’]."
"; // Replace “column_one” with the name of your first column.
$posts[$i] = “
”.$row[‘time’]."
"; // Replace “column_one” with the name of your first column.
$posts[$i] = “
”.$row[‘n’]."
"; // Replace “column_three” with the name of your third column.
$posts[$i] = “
<a href='readmore.php?storyid=”.$row[‘P_Id’]."’>Read more
"; // Your submit button. (adds one to each row)
$posts[$i] = “”;
$posts[$i] = “

”;
$i++;
}
list($pagelist,$data) = paginate($posts,10);
echo $data;
echo $pagelist;
}[/php]

Hi Smokey,

Thanks for your reply. I haven’t tried it yet because i want to fully understand the code before i do so. Do i have to create a php page called pagination.func.php? Or is this a generic function? I;ve heard the term pagination used a lot but am slightly confused by it. also where does this slot into my existing code - under the connection script?

Many thanks,

Sam

What a bozo I am sometimes… paginate file at the bottom of my post.

The code I posted is to replace the code at the end of what you posted in your previous post, from:

// Assuming you've already connected to your database: $result = mysql_query("SELECT * FROM banter ORDER BY P_Id DESC");
downwards.

paginate.func.php:
[php]<?php
/**

  • Trawls through the $data array and prints $perpage elements up to $pagelistmax, using the page number in $_GET[$get]

  • @param array $data An array containing the data to be paginated. Each element should contain 1 item/piece of data.

  • @param integer $perpage How many pieces of data to show per page.

  • @param integer $pagelistmax How many pages to show in the page navigation element.

  • @param string $prev What to show as the ‘previous page’ button.

  • @param string $next What to show as the ‘next page’ button.

  • @param string $pgsep What to use to separate the page numbers in the page navigation element.

  • @param string $get The get variable to use for page numbers.

  • @param array $ignoregets An array containing the names of get variables that you want to stay put before appending the page number get variable.

  • @return string Echos out the data paginated with the pagination options/navigation included.
    /
    function paginate($data,$perpage = 9,$pagelistmax = 5,$prev = “<”,$next = “>”,$pgsep = “,”,$get = “page”,$ignoregets = array())
    {
    if(is_array($data) && !empty($data))
    {
    $returndata = array();
    $maxpages = ceil(count($data)/$perpage);
    if($pagelistmax > $maxpages) $pagelistmax = $maxpages;
    $pagenum = (isset($_GET[$get])) ? $_GET[$get] : 1;
    if($pagenum > $maxpages || $pagenum < 1) $pagenum = 1;
    $min = $pagenum
    $perpage - $perpage;
    $max = $pagenum + $perpage;
    for($i = $min; isset($data[$i]) && $i < ($perpage * $pagenum); $i++)
    {
    $returndata[] = $data[$i];
    }

     if($pagelistmax % 2 == 0)
     {
     	$pagelistfirst = $pagenum - (($pagelistmax) / 2) + 1;
     	$pagelistlast = $pagenum + (($pagelistmax) / 2);
     }
     else
     {
     	$pagelistfirst = $pagenum - (($pagelistmax-1) / 2);
     	$pagelistlast = $pagenum + (($pagelistmax-1) / 2);
     }
     if($pagelistfirst < 1) $pagelistfirst = 1;
     if($pagelistfirst == 1) $pagelistlast = $pagelistmax;
     if($pagelistlast > $maxpages) $pagelistlast = $maxpages;
     if($pagelistlast == $maxpages) $pagelistfirst = $maxpages - ($pagelistmax-1);
     $pagelist = range($pagelistfirst,$pagelistlast);
    
     $get2 = "";
     foreach($_GET as $var => $val)
     {
     	if(trim($val) != "" && trim($var) != $get && !in_array(trim($var),$ignoregets))
     	{
     		$get2 .= trim($var)."=".trim($val)."&";
     	}
     }
     $get = $get2.$get;
     foreach($pagelist as $key => $num)
     {
     	$temp = "<a href=\"?".$get."=".$num."\" title=\"Go To Page ".$num."\">".$num."</a>";
     	if($num == $pagenum) $temp = "<span class=\"pnate_curr\" title=\"You Are Currently Viewing Page ".$num."\">".$num."</span>";
     	$pagelist[$key] = $temp;
     }
     $pagelist = implode($pgsep,$pagelist);
    
     $plist = "<p class=\"pnate_pagelist\"><span>Page: </span>".$pagelist."</p>";
     $pnum = "<p class=\"pnate_pofp\">Page: ".$pagenum." of ".$maxpages."</p>";
     $prv = ($pagenum > 1) ? "<a class=\"pnate_prev\" href=\"?".$get."=".($pagenum-1)."\" title=\"View Previous Page\">".$prev."</a>" : "<span class=\"pnate_prev disabled\" title=\"No Previous Pages Are Available\">".$prev."</span>";
     $nxt = ($pagenum < $maxpages) ? "<a class=\"pnate_next\" href=\"?".$get."=".($pagenum+1)."\" title=\"View Next Page\">".$next."</a>" : "<span class=\"pnate_next disabled\" title=\"No More Pages Are Available\">".$next."</span>";
    
     $pnate_list = '';
     
     $pnate_list .= "<div class=\"clearfix\"></div>";
     $pnate_list .= "<div class=\"pnate_pageinfo\">";
     $pnate_list .= $prv.$plist.$nxt.$pnum;
     $pnate_list .= "</div>";
     
     return array($pnate_list,implode('',$returndata));
    

    }
    else if(!is_array($data))
    {
    echo $data;
    }
    else
    {
    //No data supplied
    }
    }
    ?>[/php]

Hi Smokey,

Thank you for that.

I get this error on the home page

Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in D:\Hosting\8263933\html\bdwebsite\index.php on line 62

I have attached the new index.php code

[php]<?php
$con = mysql_connect(“host”,“username”,“password”);
if (!$con)
{
die('Could not connect: ’ . mysql_error());
}

mysql_select_db(“database”) or die(mysql_error());

	include 'paginate.func.php';
	$sql = "SELECT
				COUNT(c.*) AS n
				, b.*
			FROM
				`banter` AS b 
			INNER JOIN
				`comments` AS c
			ON
				c.`parent` = b.`P_Id`";
	$query = mysql_query($sql);
	if(mysql_num_rows($query) > 0)
	{
		$posts = array();
		$i = 0;
		while(($row = mysql_fetch_assoc($query)) !== false)
		{
			$posts[$i] = "<div id='row_div'>";
			$posts[$i] = "<div>".$row['P_Id']."</div>"; // Replace "column_one" with the name of your first column.
			$posts[$i] = "<div>".$row['story']."</div>"; // Replace "column_two" with the name of your second column.
			$posts[$i] = "<div><a href='user.php?userid=".$row['screen_name']."'>".$row['screen_name']."donkey</a></div></div>";
			$posts[$i] = "<div>".$row['date']."</div>"; // Replace "column_one" with the name of your first column.
			$posts[$i] = "<div>".$row['time']."</div>"; // Replace "column_one" with the name of your first column.
			$posts[$i] = "<div>".$row['n']."</div>"; // Replace "column_three" with the name of your third column.
			$posts[$i] = "<div><a href='readmore.php?storyid=".$row['P_Id']."'>Read more</a></div></div>"; // Your submit button. (adds one to each row)
			$posts[$i] = "</div>";
			$posts[$i] = "<br><br>";
			$i++;
		}
		list($pagelist,$data) = paginate($posts,10);
		echo $data;
		echo $pagelist;
	}

mysql_close($con);
?>[/php]

I must be close! Thank you for all your help. I hope one day I will understand all this and be as much help to someone else as the people on here have been to me.

Many thanks

Sam

My apologies - try changing “mysql_num_rows” to “mysql_affected_rows”

Hi Smokey,

No joy on that.

Warning: mysql_affected_rows(): supplied argument is not a valid MySQL-Link resource in D:\Hosting\8263933\html\bdwebsite\index.php on line 62

Sorry!

Sam

That’s strange… okay well remove that for now (that if statement, making sure to remove first and last {} as well). See if it works okay apart from that.

Sponsor our Newsletter | Privacy Policy | Terms of Service