Functions?

This is a discussion on "Functions?" within the PHP Forum section. This forum, and the thread "Functions? are both part of the Program Your Website category.



Go Back   Webforumz.com > Main Forums > Program Your Website > PHP Forum

Notices


Reply
 
LinkBack Thread Tools
  #1 (permalink)  
Old Feb 3rd, 2008, 15:13
Jack Franklin's Avatar
Resources Administrator

SuperMember
Join Date: May 2007
Location: Cornwall, England
Posts: 1,268
Blog Entries: 7
Thanks: 10
Thanked 4 Times in 4 Posts
Functions?

Me again. SOrry for all the questions, but I have to say you have all been awesome so far

WordPress uses functions for everything, like <?php wp_get_posts() ?> or whatever. On the index page, for example, this code displays the most recent post:
PHP: Select all

<?php
$display_posts_home 
= @mysql_query("SELECT contentid, contenttitle, contentintro, content, author, category, homepage, date_format(date, '%M %D, %Y') AS date FROM content WHERE homepage='Y' ORDER BY contentid DESC LIMIT 0 ,1");
if(!
$display_posts_home) {
echo 
'<h4>Error Displaying Content.' mysql_error() . '</h4>';
}
while (
$posts mysql_fetch_array($display_posts_home)) {
$contentid $posts['contentid'];
$contenttitle $posts['contenttitle'];
$contentintro $posts['contentintro'];
$content $posts['content'];
$author $posts['author'];
$category $posts['category'];
$date $posts['date'];
$comments_number =  mysql_query("SELECT count(commentsid) FROM comments WHERE commentsid = '$contentid'") or die(mysql_error());
 
$results mysql_result($comments_number"0"); 
//display
echo '<div class="post">';
echo 
'<h4 class="homepageposttitle"><a href="single.php?contentid=' $contentid '">' $contenttitle '</a>//  <span class="postdate">' $date ' // <a href="category.php?category=' $category '">' $category '</a></span></h4>';
echo 
'<p class="homepagepostintro">' $contentintro '</p>';
if (
$results==1) {
echo 
'<p class="homepagepostcomments">There has been ' $results ' Comment</p>';
} else {
echo 
'<p class="homepagepostcomments">There have been ' $results ' Comments</p>';
}
echo 
'<a class="contread" href="single.php?contentid=' $contentid '">Continue Reading "' $contenttitle ' "</a></div><hr /><br />';
}
?>
If I want to create a function, how do I do it? And how do I call upon the function?
Would it be best to create files such as functions.php and put them all in that?


Thanks, this is the last thread today, I promise!

Jack
Last Blog Entry: My Latest Project - Grilling Gurus... (Jun 11th, 2008)
Reply With Quote

  #2 (permalink)  
Old Feb 3rd, 2008, 15:19
alexgeek's Avatar
Technical Administrator

SuperMember
Join Date: Jul 2007
Location: Webforumz 24/7
Age: 15
Posts: 3,770
Blog Entries: 9
Thanks: 0
Thanked 0 Times in 0 Posts
Send a message via MSN to alexgeek
Re: Functions?

This is to declare functions:
PHP: Select all

function say($what) {
echo 
$what;
}
// and call it with
say("Hello");
// you can put anything in a function and set returns
function isTrue($b) {
if(
$b == true) { return true; } else { return false; }
}

//the following will output hi
if(isTrue(1)) { echo 'hi'; } 
Hope that helps a bit.
Last Blog Entry: 3D Chess in your browser! (Mar 14th, 2008)
Reply With Quote
  #3 (permalink)  
Old Feb 3rd, 2008, 15:24
Rakuli's Avatar
SuperMember

SuperMember
Join Date: Sep 2007
Location: Australia
Age: 24
Posts: 956
Blog Entries: 2
Thanks: 0
Thanked 0 Times in 0 Posts
Re: Functions?

You create a function using the function keyword followed by the function name and some paranthesis. You can pretty much have the function do anything you want.

Then once you have declared the function, you call it by writing the function name and some paranthesis.

PHP: Select all




// create a function called randomFunction

function randomFunction ()
{
     echo 
rand(110);
}

randomFunction();
// ^^ will echo a random number between one and ten. 
If you want to store the results of a function in a variable then you return that value from within the function

PHP: Select all



function randomFunction()
{
    return 
rand(110);
}

$myVar randomFunction();

// ^^ will hold the random number 
That's the basics... then you can start having arguments in your functions. These are pre-declared variables that will be available inside the function when you call it

PHP: Select all



function randomFunction ($min$max)
{
     return 
rand ($min$max);
}

$myVar randomFunction(10100);

// ^^ will call the function and sets $min to 10 and $max to 100.. these can be used as normal variables within the function 

If you don't want to have to send each variable you can set an argument as optional by giving it a value inside the function declaration

PHP: Select all




function randomFunction ($min$max 100// $min is required when calling the function but $max is not.. $max can still be sent if required though
{

return 
rand($min$max);
}

$myVar randomFunction (10); // Only send the minimum number and the $max number will be the default 100 

That concludes a brief look at functions :mtgreen:
Last Blog Entry: The wannabe juggler's quest (Oct 27th, 2007)
Reply With Quote
  #4 (permalink)  
Old Feb 3rd, 2008, 15:58
Jack Franklin's Avatar
Resources Administrator

SuperMember
Join Date: May 2007
Location: Cornwall, England
Posts: 1,268
Blog Entries: 7
Thanks: 10
Thanked 4 Times in 4 Posts
Re: Functions?

Thanks to both of you.
Alex, I understand your first example but not this one:
PHP: Select all

function isTrue($b) {
if(
$b == true) { return true; } else { return false; }
}

//the following will output hi
if(isTrue(1)) { echo 'hi'; } 
Rakuli, thanks for your post. Bookmarked this thread
Last Blog Entry: My Latest Project - Grilling Gurus... (Jun 11th, 2008)
Reply With Quote
  #5 (permalink)  
Old Feb 3rd, 2008, 16:12
alexgeek's Avatar
Technical Administrator

SuperMember
Join Date: Jul 2007
Location: Webforumz 24/7
Age: 15
Posts: 3,770
Blog Entries: 9
Thanks: 0
Thanked 0 Times in 0 Posts
Send a message via MSN to alexgeek
Re: Functions?

The function checks whether the value passed is true or false (0 is false, everything else is true).
If the value is true the function returns true.
So the if statement will display "hi" as 1 will be evaluated to true.
Not a very good example but you get the drift.
Last Blog Entry: 3D Chess in your browser! (Mar 14th, 2008)
Reply With Quote
  #6 (permalink)  
Old Feb 3rd, 2008, 16:15
Jack Franklin's Avatar
Resources Administrator

SuperMember
Join Date: May 2007
Location: Cornwall, England
Posts: 1,268
Blog Entries: 7
Thanks: 10
Thanked 4 Times in 4 Posts
Re: Functions?

Ok, I'm stuck again! I created my first function, which displays the most recent post:
PHP: Select all

function display_latest_post() {
echo 
'<h3 id="latestpost">Latest Post</h3>';
$display_latest_post = @mysql_query("SELECT contentid, contenttitle, contentintro, content, author, category, homepage, date_format(date, '%M %D, %Y') AS date FROM content WHERE homepage='Y' ORDER BY contentid DESC LIMIT 0 ,1");
if(!
$display_latest_post) {
echo 
'<h4>Error Displaying Content.' mysql_error() . '</h4>';
}
while (
$lat_post mysql_fetch_array($display_latest_post)) {
$contentidlat $lat_post['contentid'];
$contenttitlelat $lat_post['contenttitle'];
$contentintrolat $lat_post['contentintro'];
$contentlat $lat_post['content'];
$authorlat $lat_post['author'];
$categorylat $lat_post['category'];
$datelat $lat_post['date'];
$comments_number =  mysql_query("SELECT count(commentsid) FROM comments WHERE commentsid = '$contentid'") or die(mysql_error());
 
$results mysql_result($comments_number"0"); 
//display
echo '<div class="post">';
echo 
'<h4 class="homepageposttitle"><a href="single.php?contentid=' $contentidlat '">' $contenttitlelat '</a>//  <span class="postdate">' $datelat ' // <a href="category.php?category=' $categorylat '">' $categorylat '</a></span></h4>';
echo 
'<p class="homepagepostintro">' $contentintrolat '</p>';
if (
$results==1) {
echo 
'<p class="homepagepostcomments">There has been ' $results ' Comment</p>';
} else {
echo 
'<p class="homepagepostcomments">There have been ' $results ' Comments</p>';
}
echo 
'<a class="contread" href="single.php?contentid=' $contentidlat '">Continue Reading "' $contenttitlelat ' "</a></div><hr /><br />';
}
}
//END FUNCTION LATEST POST 
And called it, and it worked. Now, I want to create a function to display recent posts but exclude the first one. No bother, I'll copy the code from index.php to functions.php, create a new function, and call it. So, my function is:
PHP: Select all

function display_posts() {
$display_posts_home mysql_query("SELECT contentid, contenttitle, contentintro, content, author, category, homepage, date_format(date, '%M %D, %Y') AS date FROM content WHERE homepage='Y' ORDER BY contentid DESC LIMIT 1 ,$postnumber");
if(!
$display_posts_home) {
echo 
'<h4>Error Displaying Content.' mysql_error() . '</h4>';
}
while (
$posts mysql_fetch_array($display_posts_home)) {
$contentid $posts['contentid'];
$contenttitle $posts['contenttitle'];
$contentintro $posts['contentintro'];
$content $posts['content'];
$author $posts['author'];
$category $posts['category'];
$date $posts['date'];
$comments_number =  mysql_query("SELECT count(commentsid) FROM comments WHERE commentsid = '$contentid'") or die(mysql_error());
 
$results mysql_result($comments_number"0"); 
//display
echo '<div class="post">';
echo 
'<h4 class="homepageposttitle"><a href="single.php?contentid=' $contentid '">' $contenttitle '</a></h4>';
echo 
'<h5 class="homepagepostinfo"><span class="postid">#' $contentid ' |</span>  By <span class="postauthor">' $author ' </span> On: <span class="postdate">' $date '</span></h5>';
echo 
'<p class="homepagepostintro">' $contentintro '</p>';
if (
$results==1) {
echo 
'<p class="homepagepostcomments">There has been ' $results ' Comment</p>';
} else {
echo 
'<p class="homepagepostcomments">There have been ' $results ' Comments</p>';
}
echo 
'<a href="single.php?contentid=' $contentid '">Continue Reading "' $contenttitle '"</a></div>';
}

And I call it:
PHP: Select all

display_posts(); 

And get the error:
Quote:
Error Displaying Content.You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1


Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/penguin/public_html/cms/functions.php on line 42
But if I take the code in the function display_posts(), and place it in the index page, it works fine.

I'm including a file called functions.php, here it is:
PHP: Select all

<?php
function display_latest_post() {
echo 
'<h3 id="latestpost">Latest Post</h3>';
$display_latest_post = @mysql_query("SELECT contentid, contenttitle, contentintro, content, author, category, homepage, date_format(date, '%M %D, %Y') AS date FROM content WHERE homepage='Y' ORDER BY contentid DESC LIMIT 0 ,1");
if(!
$display_latest_post) {
echo 
'<h4>Error Displaying Content.' mysql_error() . '</h4>';
}
while (
$lat_post mysql_fetch_array($display_latest_post)) {
$contentidlat $lat_post['contentid'];
$contenttitlelat $lat_post['contenttitle'];
$contentintrolat $lat_post['contentintro'];
$contentlat $lat_post['content'];
$authorlat $lat_post['author'];
$categorylat $lat_post['category'];
$datelat $lat_post['date'];
$comments_number =  mysql_query("SELECT count(commentsid) FROM comments WHERE commentsid = '$contentid'") or die(mysql_error());
 
$results mysql_result($comments_number"0"); 
//display
echo '<div class="post">';
echo 
'<h4 class="homepageposttitle"><a href="single.php?contentid=' $contentidlat '">' $contenttitlelat '</a>//  <span class="postdate">' $datelat ' // <a href="category.php?category=' $categorylat '">' $categorylat '</a></span></h4>';
echo 
'<p class="homepagepostintro">' $contentintrolat '</p>';
if (
$results==1) {
echo 
'<p class="homepagepostcomments">There has been ' $results ' Comment</p>';
} else {
echo 
'<p class="homepagepostcomments">There have been ' $results ' Comments</p>';
}
echo 
'<a class="contread" href="single.php?contentid=' $contentidlat '">Continue Reading "' $contenttitlelat ' "</a></div><hr /><br />';
}
}
//END FUNCTION LATEST POST
//START FUNCTION GET HOME PAGE POSTS
function display_posts() {
$display_posts_home mysql_query("SELECT contentid, contenttitle, contentintro, content, author, category, homepage, date_format(date, '%M %D, %Y') AS date FROM content WHERE homepage='Y' ORDER BY contentid DESC LIMIT 1 ,$postnumber");
if(!
$display_posts_home) {
echo 
'<h4>Error Displaying Content.' mysql_error() . '</h4>';
}
while (
$posts mysql_fetch_array($display_posts_home)) {
$contentid $posts['contentid'];
$contenttitle $posts['contenttitle'];
$contentintro $posts['contentintro'];
$content $posts['content'];
$author $posts['author'];
$category $posts['category'];
$date $posts['date'];
$comments_number =  mysql_query("SELECT count(commentsid) FROM comments WHERE commentsid = '$contentid'") or die(mysql_error());
 
$results mysql_result($comments_number"0"); 
//display
echo '<div class="post">';
echo 
'<h4 class="homepageposttitle"><a href="single.php?contentid=' $contentid '">' $contenttitle '</a></h4>';
echo 
'<h5 class="homepagepostinfo"><span class="postid">#' $contentid ' |</span>  By <span class="postauthor">' $author ' </span> On: <span class="postdate">' $date '</span></h5>';
echo 
'<p class="homepagepostintro">' $contentintro '</p>';
if (
$results==1) {
echo 
'<p class="homepagepostcomments">There has been ' $results ' Comment</p>';
} else {
echo 
'<p class="homepagepostcomments">There have been ' $results ' Comments</p>';
}
echo 
'<a href="single.php?contentid=' $contentid '">Continue Reading "' $contenttitle '"</a></div>';
}
}
 
?>
And the index page is simply:
PHP: Select all

<?php include('header.php'); ?>
<div id="wrapper">
<?php include('navigation.php'); ?>
<div id="maincontent">
<?php
echo '<h2 id="introheader">' $introheader '</h2>';
echo 
'<p id="introtext">' $introtext '</p>';
display_latest_post();
display_posts();
?>
</div><!--end main content-->
<?php include('sidebar.php'); ?>
</div><!--end wrapper-->
<?php include('footer.php'); ?>
</body>
</html>

I appreciate that is a huge amount of code but help would be nice

Thanks, Jack
Last Blog Entry: My Latest Project - Grilling Gurus... (Jun 11th, 2008)
Reply With Quote
  #7 (permalink)  
Old Feb 3rd, 2008, 16:28
Jack Franklin's Avatar
Resources Administrator

SuperMember
Join Date: May 2007
Location: Cornwall, England
Posts: 1,268
Blog Entries: 7
Thanks: 10
Thanked 4 Times in 4 Posts
Re: Functions?

OK, I have it narrowed down
If I replace:
PHP: Select all

$display_posts_home mysql_query("SELECT contentid, contenttitle, contentintro, content, author, category, homepage, date_format(date, '%M %D, %Y') AS date FROM content WHERE homepage='Y' ORDER BY contentid DESC LIMIT 1 ,$postnumber"); 

With:
PHP: Select all

$display_posts_home mysql_query("SELECT contentid, contenttitle, contentintro, content, author, category, homepage, date_format(date, '%M %D, %Y') AS date FROM content WHERE homepage='Y' ORDER BY contentid DESC LIMIT 1 ,5"); 

It works. But I want that variable to be included because it adds user control. Why does it work on the home page but not functions.php?

The $postvariable is stored in config.php, and on the home page these are included like so:
PHP: Select all

<?php include('config.php'); ?>
<?php 
include('functions.php'); ?>
rest of code..., doctype, head, body, etc
Would that have anything to do with it?

Jack
Last Blog Entry: My Latest Project - Grilling Gurus... (Jun 11th, 2008)
Reply With Quote
  #8 (permalink)  
Old Feb 3rd, 2008, 16:30
alexgeek's Avatar
Technical Administrator

SuperMember
Join Date: Jul 2007
Location: Webforumz 24/7
Age: 15
Posts: 3,770
Blog Entries: 9
Thanks: 0
Thanked 0 Times in 0 Posts
Send a message via MSN to alexgeek
Re: Functions?

Any varialbles no defined in the function must be declared as global.
e.g.
PHP: Select all

$hi "hey!";
function 
hello() {
echo 
$hi;
}
hello();
/// Will not work


$hi "hey!";
function 
hello() {
global 
$hi;
echo 
$hi;
}
hello();

//will work! 
Last Blog Entry: 3D Chess in your browser! (Mar 14th, 2008)
Reply With Quote
  #9 (permalink)  
Old Feb 3rd, 2008, 16:31
Jack Franklin's Avatar
Resources Administrator

SuperMember
Join Date: May 2007
Location: Cornwall, England
Posts: 1,268
Blog Entries: 7
Thanks: 10
Thanked 4 Times in 4 Posts
Re: Functions?

YES! Thanks Alex.

Stand by for more questions this evening though!
Last Blog Entry: My Latest Project - Grilling Gurus... (Jun 11th, 2008)
Reply With Quote
  #10 (permalink)  
Old Feb 3rd, 2008, 16:35
marSoul's Avatar
Moderator
Join Date: Sep 2007
Location: Tehran - Iran
Age: 28
Posts: 411
Blog Entries: 2
Thanks: 4
Thanked 4 Times in 4 Posts
Send a message via MSN to marSoul Send a message via Yahoo to marSoul
Re: Functions?

I think the problem is because of the database connection, try to define a connection include file and make it global in your function, like :

PHP: Select all

<?php /*Create a connection*/?>
<?php
    $connection 
mysql_connect(DB_SERVER,DB_USER,DB_PASS);
    if (!
$connection) {
        die(
"Database Connection Failed : " mysql_error());
    }
?>

<?php /*Select database*/?>
<?php
    $db_select 
mysql_select_db(DB_NAME,$connection);
    if (!
$db_select) {
        die(
"Database Selection Failed : " mysql_error());
    }
?>
then in your function :

PHP: Select all

function function_name() {
        global 
$connection;
        
$query "YOUR QUERY";
        
$result_query mysql_query($query $connection);
        ...

__________________
Designing For Communicating
Website : http://www.datisdesign.com
Weblog : http://blog.datisdesign.com

Last Blog Entry: Throughout IRAN (Dec 10th, 2007)
Reply With Quote
  #11 (permalink)  
Old Feb 3rd, 2008, 16:49