[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

$GLOBAL mysql_connect from include()

Posted on 2007-09-30
10
Medium Priority
?
711 Views
Last Modified: 2013-12-13
Hi all. I'm learning php and can't figure this out.

From home.php I am calling functions.inc.php where within functions.inc.php I have the following:-

function conn()
      {            
       @$conn=mysql_connect($GLOBAL['localhost'],$GLOBAL['root'],$GLOBAL ['1540158']);
      
      // Check server connection status. Provide message if fault.
                                       
      if (!$conn)
      
      
            {
            echo '
                  Sorry, at the moment we are unable to connect to the server at this time.'."\n".'<body>'."\n".'<html>';
            exit;
            }
      }


If I try and use this from within home.php  am not getting $conn as GLOBAL

As this is the case, if I try the following mysql_select_db($db,$conn) the script breaks and I receive the following.

Notice: Undefined variable: conn in D:\htdocs\Nusphere\register-user.php on line 68

Warning: mysql_select_db() [function.mysql-select-db]: Access denied for user 'ODBC'@'localhost' (using password: NO) in D:\htdocs\Nusphere\register-user.php on line 69

Warning: mysql_select_db() [function.mysql-select-db]: A link to the server could not be established in D:\htdocs\Nusphere\register-user.php on line 69
Sorry, we are unable to connect to the database at the moment. Please try later..

I know that this is a scope problem but can't see how I need to change the function so that it works.

Help much appreciated.

Jezella
0
Comment
Question by:jezella
  • 5
  • 4
10 Comments
 
LVL 24

Expert Comment

by:glcummins
ID: 19987555
Is $GLOBAL a variable that you have defined elsewhere? If so, you need to include it within the scope of this function by using the 'global' keyword:

function conn()
{
  global $GLOBAL;
  ...
}

As your function currently stands, the $GLOBAL variable does not exist in the scope of your function, so the values you are attempting to access within it are invalid.
0
 
LVL 9

Expert Comment

by:Alex
ID: 19989036
<?php

        // Set the variables for the database

        $Host      = "localhost";
        $User      = "";
        $Password  = "";
        $DBName    = ""; // Database name

    $Link = mysql_connect($Host, $User, $Password) or die(mysql_errno() . ": ". mysql_error());
    mysql_select_db($DBName, $Link) or die(mysql_errno() . ": ". mysql_error());

?>

save it as myconn.php for example and then include it to every php you want like this:

include "myconn.php" or require "myconn.php"
0
 

Author Comment

by:jezella
ID: 19990885
Thanks to both for the input here.

I have now tried the following and this appears to work though I am not sure as to how secure this would be from a security point.

function conn()
      {
      global $conn;
      global $host;
      global $user;
      global $pass;
      
      $conn=mysql_connect($host, $user,$pass);

      if (!$conn)
            echo 'Error in connection to Server';
      }

The initial question may not have been very clear where what I want to do is create a function that makes a connection to mysql without selecting a database.  The conn() function would be in my functions.php and include('functions.php') would be in home.php .

The above code seems to work through a better user (I think) of global and is developed further with $host, $user and $pass.

My initial problem was that I was not passing $conn back to home.php so that it could be used by mysql_select_db('members',$conn) .  Here $conn was, in my first code example, not global.

Now, given the above example code, is my use of global correct as I feel that this may be a security problem and especially so with $host, $user and $pass.

Getting better but far from good.

Jezella
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 24

Expert Comment

by:glcummins
ID: 19990921
Yes, your use of the global keyword is correct (except for 'global $conn'). It is not a security issue, because global just makes a variable available in the scope of this function that is not normally available. However, the variable still needs to be defined elsewhere in the script. An alternative is to just pass the desired variables to the function in this manner:

function conn($host, $user, $pass)
{
  $conn = mysql_connect($host, $user, $pass);

  ...  // Connect to the server

  return $conn;
}

Either method will function identically.
0
 

Author Comment

by:jezella
ID: 19991258
glcummins your time really is appreciated and yes the above does work without problems.  I'm using NuSphere PhpED to step through my code.

From my index.php when I call conn() a connection to the db is made.

If in a following line I use mysql_select_db('members') this then selects the members db without problems.

If however, I do the following mysql_select_db('members',$conn) so using the optional link_identifier, the code breaks.  This leads me to think that $conn is not being returned.

I understand that the link_identifier is optional but my understanding is that mysql_select_db() will use a previous open connection where, should this not exist, then the optional link_identifier will be used where in this case, this is $conn.

Forgive me, I'm learning.

Jezella
0
 
LVL 24

Expert Comment

by:glcummins
ID: 19991321
Are you able to show me how you are calling the function conn? Specifically, you need to be sure that you are assigning the returned connection to a variable. Something like this:

$conn = conn();

mysql_select_db('members', $conn);
0
 
LVL 24

Expert Comment

by:glcummins
ID: 19991329
BTW, I'll not forgive you for learning. It's the ones who refuse to learn that should be asking for forgiveness. :)
0
 

Author Comment

by:jezella
ID: 19991350
glcummins, kind words, thanks you

I tried the following and this does allow me to use the optional link_identifier.

function conn()
            {global $conn;
$conn=mysql_connect('localhost' ,'root','280158');
            return $conn;

            if (!$conn)
                  echo 'Error in connection to Server';
            }
0
 
LVL 24

Accepted Solution

by:
glcummins earned 2000 total points
ID: 19991529
Okay, that will work. In this case, you don't actually need to return $conn at the end of the function since you are declaring it to be global at the start of the function.

There are two ways to make a variable available outside of a function. Here are two examples showing the different methods:

Example 1:

<?php

$myvariable = 1;

displayVariable($myvariable);  // Output: "The value of 'myvariable' is 1"

function displayVariable($myvariable)
{
   echo "The value of 'myvariable' is $myvariable.";
}

?>

In this example, we passed the variable in as a parameter to the function, so it is available in the script.


Example 2:

<?php

$myvariable = 1;

displayVariable(); // Output: "The value of 'myvariable' is 1"

function displayVariable()
{
  global $myvariable;
   echo "The value of 'myvariable' is $myvariable.";
}

?>

In this example, we did not pass the variable into the function as a parameter. Instead, we used the 'global' keyword to take the variable that had been defined elsewhere and make it available in this function.

Now take a look at a third example:

<?php

$myvariable = 1;

displayVariable();

function displayVariable()
{
   echo "The value of 'myvariable' is $myvariable.";
}

?>

The output of this script is:

 The value of 'myvariable' is .

Additionally, you will probably get a notice about the variable $myvariable being undefined. Why? Because we neither passed the variable into the function as a parameter, nor declared it using the 'global' keyword. This means that the function displayVariable() knows nothing about the variable, even though it has been defined elsewhere in the script.

In conclusion, while your response above will work, you only need to use the global keyword, OR return the value of $conn at the end of the function, but not both. If you return the value, be sure to assign it when you call the function, like this:

$conn = conn();
0
 

Author Comment

by:jezella
ID: 19991852
glcummins.  This really must be the most perfect answer ever and I am so greatful.  I am reading PHP and Mysql Web Development by Luke Welling and Laura Thomson, a very good book indeed.

Much of your examples above I understand from the reading of this book.  However, three points you mentioned have helped no end.

1) The use of the global OR return keywords where this is one or the other.
2) $conn = conn().  Here I had not even considered that I needed to declare the function and this was my biggest problem.
3) I have my php.ini to strict and all error checking.  Basically so I learn to write code without error messages popping up all over the place.  I know that this would need a lesser setting in the real world.  But here, I could not understand why I was receiving notices for variable not being declared.  Your explanation of this also was very helpful.

Your help really is appreciated and even though I go back to earlier pages in the book, (very frequently) each time I do so, along with help from people such as yourself, my understanding of the subject improves.  But need I mention this.

Many thanks.

Jezella.  
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to count occurrences of each item in an array.
Suggested Courses
Course of the Month17 days, 16 hours left to enroll

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question