Page 1 of 1
placing mysql query inside a function
Posted: Fri Feb 06, 2004 9:31 pm
by dsdsdsdsd
hello; I have a query that works fine unless I put it inside of a function;
here it is inside of a function which will give 'bad' as an output;
Code: Select all
<?php
function create_table ($the_table)
{ $query = "create table $the_table (create definition , ... )";
if ( mysql_db_query($database , $query , $link))
{echo ("&oppie=good");
}
else
{echo ("&oppie=bad");
}
}
create_table($table_name);
?>
my question: do mysql queries not work if they are inside of a function?
thanks
dsdsdsdsd
Posted: Fri Feb 06, 2004 11:14 pm
by d3ad1ysp0rk
did you give $table_name a value?
Posted: Sat Feb 07, 2004 7:16 am
by McGruff
Functions have their own local scope. That means any vars you want to use in the function must be passed in, or defined inside the fn.
$database and $link haven't been passed in or defined hence the query won't work.
If you had error reporting turned up to E_ALL you would have got a warning about this (always dveleop with E_ALL - but turn down on a live site).
Posted: Mon Feb 09, 2004 2:02 pm
by dsdsdsdsd
mcgruff,
thanks for your response; I did not pass those vars in because I presumed that they were global since they had been defined outside of the function;
also, what is E_ALL?
lilpunkskater; thanks for your response; yes, $table_name had been defined, however I did not show that in my posted script;
thanks
dsdsdsdsd
Posted: Mon Feb 09, 2004 2:12 pm
by McGruff
If you're working on a local server look in your php.ini file, you'll find an error_reporting setting. E_ALL is the maximum setting and is pretty much essential for development.
Posted: Mon Feb 09, 2004 3:26 pm
by Saethyr
E_ALL is an error reporting level.
Table 1. error_reporting() level constants and bit values
value constant
1 E_ERROR
2 E_WARNING
4 E_PARSE
8 E_NOTICE
16 E_CORE_ERROR
32 E_CORE_WARNING
64 E_COMPILE_ERROR
128 E_COMPILE_WARNING
256 E_USER_ERROR
512 E_USER_WARNING
1024 E_USER_NOTICE
2047 E_ALL
2048 E_STRICT
Posted: Mon Feb 09, 2004 7:13 pm
by d3ad1ysp0rk
$database and $link are not defined INSIDE the function.
They made be defined outside, but if thats true, you'll need to send them in the function also..
ie. create_table($tablename,$database,$link);
or just define them inside the function if you're only gonna be using one db..
Posted: Tue Feb 10, 2004 6:37 am
by mahara
You need not always pass the variables to a function by using function parameters or create it within a function. The use of 'global' make sure that variable(s) you specify is/are in global scope within the function.
Code: Select all
<?php
function create_table ($the_table)
{
global $query, $link;
$query = "create table $the_table (create definition , ... )";
if ( mysql_db_query($database , $query , $link))
{
echo ("&oppie=good");
}
else
{
echo ("&oppie=bad");
}
}
create_table($table_name);
?>