...

View Full Version : sql code not working in a function ?!?!?



snoodle
07-21-2007, 03:03 AM
this is driving me nuts...

If I execute the following code...

function MyFunc()
{
echo "inside MyFunc - ";
// $sql = "INSERT INTO test (aline) VALUES('mary had a little lamb')";
// $result = $database->query($sql);
}


// Parse the incoming data
$q=$_GET["q"];
parse_str($q);

$sql = "DELETE from test";
$result = $database->query($sql);

MyFunc();

$sql = "INSERT INTO test (aline) VALUES('mary had a little lamb')";
$result = $database->query($sql);

echo "All Done";
---------------------------------------------
Everything works fine... "mary had a little lamb" gets put in the table called "test", and the responsetext in my ajax code gets "MyFunc - All Done".
--------------------------------------------------
However, if I uncomment those lines above that insert the 'mary had a little lamb' from within the function, nothing happens (I get a <br> in my responsetext and the db does not get updated. BTW, the reference to $database is just my database object that has the connection already set up and all that. I know this seems like a really dumb question, but it is really making me crazy as I try every iteration possible. I was hoping someone would see something simple going on that I'm simply not seeing.

Mwnciau
07-21-2007, 03:13 AM
I think the problem may be that your $database object can't be accessed from within the function, in your function add to the start:


global $database;

snoodle
07-21-2007, 09:42 AM
THANK YOU! Mann, that was driving me nuts. It does seem a bit weird to me though. If a procedure or method of an object is accessing another object, it has to always include the "global $obj" inside the procedure/method? Alrighty, whatever works I guess.

Thanks again.

Mwnciau
07-21-2007, 12:54 PM
It's because the inside of functions is totally separate to the rest of your code, apart from the parameters of the function.

PappaJohn
07-21-2007, 04:53 PM
For more info on variable scope:
http://www.php.net/manual/en/language.variables.scope.php

snoodle
07-21-2007, 05:58 PM
I see. what about globals? Is the best way to handle arguments that you want to share between functions to simply make the whole thing a class?



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum