Why must I put the database connection file in the function body when calling a function?

Source: Internet
Author: User
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 );}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.