Jump to content

[SOLVED] Functions transferring variables


cliftonbazaar

Recommended Posts

On every single one of my web pages I need to open a database, get the values and then close the database.

To do this I thought I might have 2 functions top() and bottom(); the top() function shows everything that should happen at the top of the page

function top(){  //This is the function for the top of all the pages
    session_start();
    ini_set('display_errors', 1);//use these while debugging
    error_reporting(E_ALL);//use these while debugging
  
    //Now we will connect to the database
    $sqldb = mysql_connect("localhost", "user", "better_not_show_this_on_a_public_forum");  //Connect to the database
    mysql_select_db("kingdoms", $sqldb);  //Select which database we wish to use

    //Check to see if the log in details are correct
    $check_player = mysql_query("SELECT * FROM players");  //Load all the records into the array so we can check them
    WHILE($user = mysql_fetch_array($check_player)) { //Lets loop through all the records
      IF ($_SESSION['userName']==$user['characterName']) break;  //We have a winner!
    }

    IF (empty($_SESSION['characterName'])) {  //If there is no user name then there is an error
      header('Location:http://www.kingdoms.cliftonbazaar.com/error.php');
      die();
    }
  }

 

While the bottom() simply closes the database

function bottom() {mysql_close($sqldb);}  //This is the function at the bottom of each page

 

But when I run the page I get a warning that $sqldb is a 'undefined variable' in bottom().

 

How can I get this to work?

Link to comment
https://forums.phpfreaks.com/topic/154565-solved-functions-transferring-variables/
Share on other sites

The variable $sqldb is local to the function top(). What you should do is return it at the end of the function so it can be passed to the function bottom().

 

<?php
function top() {
//
// your code
//
    return ($sqldb);
}

function bottom($sqldb) {
//
// your code
//
}

$sqldb = top();
//
// your code
//
bottom($sqldb);
?>

 

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.