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

07-21-2007, 04: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

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


$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.

07-21-2007, 04: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;

07-21-2007, 10: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.

07-21-2007, 01: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.

07-21-2007, 05:53 PM
For more info on variable scope:

07-21-2007, 06: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?