Jump to content


Photo

creating a function


  • Please log in to reply
3 replies to this topic

#1 blue_seraph

blue_seraph
  • New Members
  • Pip
  • Newbie
  • 2 posts

Posted 30 March 2006 - 03:02 AM

I need to get simular data from a data base on many pages on my site
I descided to make a function so I wont need to right the same code over and over
I know the function works i just dont know how to get the data out


function getAllItems($what,$where,$ordered){
$query = "SELECT * FROM `items` where `$what`= '$where' ORDER BY '$ordered'";
$result = mysql_query($query);
$i=0;
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$id[$i]=$row[id];
$cat[$i]=$row[category];
$pName[$i]=$row[prodname];
$smallD[$i]=$row[smalldescript];
$longD[$i]=$row[longdescript];
$pImage[$i]=$row[image];
$price[$i]=$row[price];
$i++;
}
$gAI=$i;
}
--------------------------------------------------

This is how i am retreiving the data

--------------------------------------------------
getAllItems("category","Hookah Flavors","prodname");

<?
for ($i=0;$i<=$gAI;$i++){
?>
<li><a href="flavors.php?id=<?=$id[$i]?>" target="hookahflavors"><li><?=$pName[$i]?></a></li>
<?}?>
--------------------------------------------------

The data being retrieved is product info
How do i save the arrays from the function so they can be used afterwords
I want to use this funtion to create dynamic index pages for all the categories

--------------------------------------------------

#2 akitchin

akitchin
  • Staff Alumni
  • Advanced Member
  • 2,516 posts
  • LocationCalgary, AB, Canada

Posted 30 March 2006 - 03:21 AM

this is a fairly basic part of functions - i would suggest reading a little more about custom functions.

what you're after is the return statement. when you return something, it is sent back as info to the scope that called it. for example:

function two_plus_two()
{
  $value = 2 + 2;
  return $value;
}

$four = two_plus_two();

by returning $value in the function, calling two_plus_two() gives $value to whatever it is assigned. it is also possible to use it directly, rather than assigning it to a variable:

$eight = 2 * two_plus_two();


#3 blue_seraph

blue_seraph
  • New Members
  • Pip
  • Newbie
  • 2 posts

Posted 30 March 2006 - 04:19 AM

i know i can do
$four = two_plus_two();


but i have 7 array that the funtion creates that i need to be able to use after the funtion

$id[] and $pname[] in this case

<?
for ($i=0;$i<=$gAI;$i++){
?>
<li><a href="flavors.php?id=<?=$id[$i]?>" target="hookahflavors"><li><?=$pName[$i]?></a></li>
<?}?>

i'll have to use the rest of the arrays latter


#4 Guest_footballkid4_*

Guest_footballkid4_*
  • Guests

Posted 30 March 2006 - 05:41 AM

Return all of the arrays in another array:
<?php
function your_function()
{
     $id = array();
     $pname = array();
     //other variables
     return array( $id , $pname );
}
?>





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users