I’m new to using functions, so – no judgements please ;).
Let’s say I have a function add_to_x() in function.php which within performs a mysql_query(). This function is included, (include "function.php";), into script.php, and called mid-way through that script. At the top of function.php I establish a database connection, closing it at the end.
Would this be passed through by default to the function add_to_x() or would I need to establish and close a connection within add_to_x() itself?
For illustration and good measure:
Contents of script.php
include "function.php";
// Do something
add_to_x($arg1, $arg2);
// Do something else
Contents of function.php
include "db_conn.php";
$conn = mysql_connect($db_host, $db_user, $db_pass); mysql_select_db($db_name);
function add_to_x($arg1, $arg2) {
// Do something
$query = "SELECT * FROM table WHERE x = '$arg1'";
$result = mysql_query($query);
}
mysql_close($conn);
Would that work? Or would I need to do something like this:
function add_to_x($arg1, $arg2) {
include "db_conn.php";
$conn = mysql_connect($db_host, $db_user, $db_pass); mysql_select_db($db_name);
// Do something
$query = "SELECT * FROM table WHERE x = '$arg1'";
$result = mysql_query($query)
mysql_close($conn);
}
It might look like a rather stupid question, but I’m not sure of the scope of connections/functions. I feel that perhaps the second example would be better practice even if the first would work?
Any comments, advice, answers would be greatly appreciated! (I realize I’ve made this question a bit messy, but I hope the illustration code helps, and of course, if you need further clarification please do ask for it)!
You can open the database connection in the file that defines your functions, as you are doing. But closing it at the end of
function.phpis not what you want to do – by doing this you are closing the connection before it is ever used.You would either call
mysql_close()at the very end of your main script (after all calls to functions that require the connection), or not at all (the resource will be implicitly closed/freed when the script finishes).