Why do I have to put the database connection file in the function body when calling a function like the following program: & lt ;? & Nbsp; header ("Content-type: & nbsp; text/html; & nbsp; charset = gb2312"); & nbsp; $ act = $ _ GET ["act"]; why must I put the database connection file in the function body when calling a function?
Like the following program:
Header ("Content-type: text/html; charset = gb2312 ");
$ Act = $ _ GET ["act"];
If ($ act = "del") {// delete a record
$ Id = $ _ GET ["id"];
Require ('Conn. php ');
$ Conn-> query ("delete from lyb where id = $ id ");
Fy ();}
If ($ act = "list") {fy ();}
Function fy (){
Require ('Conn. php ');
$ SQL = "select * from lyb order by ID desc ";
// Echo $ SQL;
$ Result = $ conn-> query ($ SQL );}
If you write require ('Conn. php'); outside the function, it will not work, as shown below. In this way, if there are several if statements, require ('Conn. php'); it is inconvenient to write them several times. I remember that a function without any parameters and no return value is equivalent to inserting the code in the function body to the position where the function is called, but this is not the case here.
Header ("Content-type: text/html; charset = gb2312 ");
Require ('Conn. php ');
$ Act = $ _ GET ["act"];
If ($ act = "del") {// delete a record
$ Id = $ _ GET ["id"];
$ Conn-> query ("delete from lyb where id = $ id ");
Fy ();}
If ($ act = "list") {fy ();}
Function fy (){
$ SQL = "select * from lyb order by ID desc ";
// Echo $ SQL;
$ Result = $ conn-> query ($ SQL );}
Share:
------ Solution --------------------
$ Con is the global variable. Of course not available in the function body. Change to this
Function fy (){
Global $ conn;
$ SQL = "select * from lyb order by ID desc ";
// Echo $ SQL;
$ Result = $ conn-> query ($ SQL );}