php function help

Associate
Joined
19 Jul 2006
Posts
1,847
I have a page and an include file and im trying to make a function to make my code reusable.

original code in full that works
Code:
<?php 
$result = mysql_query("SELECT price FROM catalogue WHERE item = 'whitetshirt'");
if (!$result) {
    die("no such field");
}

$Row = mysql_fetch_array( $result );
$Displayprice = $Row['price']/100;

echo "£$Displayprice";

I tried spliting it up
this is in my include file
Code:
<?php
function itemdisplayprice(){
$Row = mysql_fetch_array( $result );
$Displayprice = $Row['price']/100;
// convert price from pence to pounds
echo "£$Displayprice";
}
?>

in proper page
Code:
<?php 
				 
$result = mysql_query("SELECT price FROM catalogue WHERE item = 'whitetshirt'");
if (!$result) {
    die("No such feild");
}
				itemdisplayprice
				?>
 
PHP:
<?php
function itemdisplayprice($result)
{
  $Row = mysql_fetch_array( $result );
  $Displayprice = $Row['price']/100;
  // convert price from pence to pounds
  echo "£$Displayprice";
}
?>

PHP:
<?php 
$result = mysql_query("SELECT price FROM catalogue WHERE item = 'whitetshirt'");
if (!$result) {
    die("No such feild");
}
itemdisplayprice($result);
?>
I think that should work, been a while since I've looked at PHP function passes.

The problem was that you weren't passing the result of your MySQL query to the function so it was trying to use a variable that doesn't exist.

The only way a function can access a variable outside of itself is if that variable is declared global. Otherwise the only things it can access are variables passed in as parameters.
 
Last edited:
Back
Top Bottom