Page 1 of 1

Problem with Query inside a function

Posted: Sat Nov 19, 2011 8:32 pm
by MikeD
Trying to simplify my battles by using a function, however when I call the function as

Code: Select all

meleeattack($player1,$player2)
or vice versa.

It comes up with undefined variables $a and $b. Which should be replaced by $player1 and $player2

I'm not very experienced with function, so I'm not sure if I'm missing something or what.

Here's the part of the function.

Code: Select all

function meleeattack($a,$b){ global $db, $player1, $player2; }
{
$a1="SELECT * FROM `characters` WHERE `charname`='$a'";
$a2=mysqli_query($db,$a1) or die (mysqli_error($db));
$a3=mysqli_fetch_array($a2);

$wep="SELECT * FROM `playeritems` WHERE `charname`='$a' AND `atype`='weapon' AND `equip`='1'";
$wep2=mysqli_query($db,$wep) or die (mysqli_error($db));
$wep3=mysqli_fetch_array($wep2);

$b1="SELECT * FROM `characters` WHERE `charname`='$b'";
$b2=mysqli_query($db,$b1) or die (mysqli_error($db));
$b3=mysqli_fetch_array($b2);
}

Re: Problem with Query inside a function

Posted: Sat Nov 19, 2011 8:44 pm
by Ark
I'm not sure what are globals i'd just heard they're bad, maybe try this?

Code: Select all

function meleeattack($a,$b,$db)
{
$a1="SELECT * FROM `characters` WHERE `charname`='$a'";
$a2=mysqli_query($db,$a1) or die (mysqli_error($db));
$a3=mysqli_fetch_array($a2);

$wep="SELECT * FROM `playeritems` WHERE `charname`='$a' AND `atype`='weapon' AND `equip`='1'";
$wep2=mysqli_query($db,$wep) or die (mysqli_error($db));
$wep3=mysqli_fetch_array($wep2);

$b1="SELECT * FROM `characters` WHERE `charname`='$b'";
$b2=mysqli_query($db,$b1) or die (mysqli_error($db));
$b3=mysqli_fetch_array($b2);
} 

Re: Problem with Query inside a function

Posted: Sat Nov 19, 2011 8:54 pm
by Jackolantern
Ark is right. I am not sure what you were doing with the small block and then the longer block after it, but it should probably look like this:

Code: Select all

function meleeattack($db, $a, $b)
{
$a1="SELECT * FROM `characters` WHERE `charname`='$a'";
$a2=mysqli_query($db,$a1) or die (mysqli_error($db));
$a3=mysqli_fetch_array($a2);

$wep="SELECT * FROM `playeritems` WHERE `charname`='$a' AND `atype`='weapon' AND `equip`='1'";
$wep2=mysqli_query($db,$wep) or die (mysqli_error($db));
$wep3=mysqli_fetch_array($wep2);

$b1="SELECT * FROM `characters` WHERE `charname`='$b'";
$b2=mysqli_query($db,$b1) or die (mysqli_error($db));
$b3=mysqli_fetch_array($b2);
}