Problem with Query inside a function

Place for questions and answers for all newcomers and new coders. This is a free for all forum, no question is too stupid and to noob.
Post Reply
User avatar
MikeD
Posts: 294
Joined: Thu Sep 08, 2011 4:28 am

Problem with Query inside a function

Post 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);
}
User avatar
Ark
Posts: 427
Joined: Wed Jun 01, 2011 10:25 pm

Re: Problem with Query inside a function

Post 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);
} 
Orgullo Catracho
User avatar
Jackolantern
Posts: 10891
Joined: Wed Jul 01, 2009 11:00 pm

Re: Problem with Query inside a function

Post 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);
} 
The indelible lord of tl;dr
Post Reply

Return to “Beginner Help and Support”