Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

DB Connection in Function Call 1

Status
Not open for further replies.

Marine1969

IS-IT--Management
Mar 5, 2015
60
US
I have a page that is dedicated to record maintenance. I have 3 tables where 1 is the main record and the other 2 are multiple records attached to a single record in the main. IE. cstOrders, orderParts, orderServices. When any of the 3 tables get changed (parts added, deleted or edited) I want created a function to calculate the total. My issue is that once it gets to the function it throws the error...

Notice: Undefined variable: conn in /var/ on line 9

I have on line 2 which connects to the database,
PHP:
include "db_connect.php";
.
This include works flawlessly until now. Is there some reason why I am getting the Undefined variable for my connection?
 
Hi

Sounds like a scope issue. In PHP the functions can not access global scope by default, only on special request ( see the [tt]global[/tt] keyword ) :
PHP:
[teal]<?php[/teal]

[red]include[/red] [i][green]"db_connect.php"[/green][/i][teal];[/teal]

[b]function[/b] [COLOR=orange]whatever[/color][teal]([/teal][navy]$str[/navy][teal])[/teal]
[teal]{[/teal]
    [highlight][b]global[/b] [navy]$conn[/navy][teal];[/teal][/highlight]

    [navy]$conn[/navy][teal]->[/teal][COLOR=orange]prepare[/color][teal]([/teal][navy]$str[/navy][teal]);[/teal]
    [gray]// ...[/gray]
[teal]}[/teal]

But hard to guess without seeing more code, specially the variable and function declaration.


Feherke.
feherke.github.io
 
That did the trick. Thank you.


Since I am using the connection in the include is there a drawback to changing "$conn" to "global $conn" in the file?
 
Hi

You mean to add [tt]global $conn;[/tt] directly in db_connect.php so you not have to add it in each function that will use $conn ? No, it not works like that. The [tt]global[/tt] keyword is not like the [tt]public[/tt] keyword, it not modifies the visibility of the enumerated variables; they are already global anyway if you declared them in the global scope. The keyword says that the enumerated variables instead of referring to the current scope's variables, will refer to the global ones. So you have to do this again and again when inside a function need global variable.

Alternatively you may use the [tt]$GLOBALS[/tt] superglobal.

Feherke.
feherke.github.io
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top