Simple php problem with database config file

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
kday
Forum Newbie
Posts: 8
Joined: Tue Oct 24, 2006 5:47 pm

Simple php problem with database config file

Post by kday »

This question should be an easy one to answer, but I can't seem to find it.

Ok, so I have a config file called variables.php. It looks something like this:

Code: Select all

<?php

$base_dir = "/";
$db = "my_database";
$db_user = "root";
$db_loc = "localhost";
$db_pass = "";

?>
I also have another php file in the same directory. I want to require variables.php into this file, so I put:

Code: Select all

<?php require_once('variables.php'); ?>
Now in this file, I have a class that looks something like this:

Code: Select all

<?php

class myClassName {
  function my_function() {
    // function code
  }
}

?>
For an example, something like this will work:

Code: Select all

<?php

require_once('variables.php');
echo $db; // Successfully echo's the $db variable in variables.php

?>
Something like this will not work:

Code: Select all

<?php

require_once('variables.php');

class myClassName {
  function my_function() {
    echo $db; // Throws an error saying it can't find the $db variable
  }
}

?>
Now my question is what do I do to make my variables.php file accessible from an external class?

-Kyle
nickvd
DevNet Resident
Posts: 1027
Joined: Thu Mar 10, 2005 5:27 pm
Location: Southern Ontario
Contact:

Post by nickvd »

I won't give you the answer, but I will assign a reading assignment for homework... I expect a 500 word essay on the meaning of Variable Scope (no, not the green liquid)
kday
Forum Newbie
Posts: 8
Joined: Tue Oct 24, 2006 5:47 pm

Post by kday »

I read through that, but I am still confused. I know I can't access those variables since they aren't global. I also know how to access the variables if I put my variables.php in a class and create a class object within my other php file. I just don't think this is the proper way to do it (or is it?). I've also been thinking of using the predefined $GLOBALS array, but I don't believe this the best practice. Can someone who knows there stuff just help me out and point me in the right direction? At the moment, I don't plan on using a true Views, Models, Controllers system such as CakePHP. I am just experimenting with the basics, and trying to learn things.

So I guess my problem isn't that I can't figure out how to access these variables.... I am just confused on the proper way of doing it.

-Kyle
kday
Forum Newbie
Posts: 8
Joined: Tue Oct 24, 2006 5:47 pm

Post by kday »

I would also like to note that if I add "global $db, $db_user, $db_loc, $db_pass;" to the top of every function, everything works fine.... This just seems verbose and again, not the right way to do things.

Here is my php file:

Code: Select all

<?php

require_once("variables.php");

class indexController {
  function show($x) {
    global $db, $db_user, $db_loc, $db_pass;
    $link = mysql_connect($db_loc, $db_user, $db_pass);
    mysql_select_db($db, $link);
    $query = mysql_query("SELECT $x FROM woots ORDER BY id DESC LIMIT 1", $link) or die(mysql_error());
  	$result = mysql_fetch_array($query);
  	return $result[0];
  	@mysql_close($link);
  	@mysql_free_result($result);
  }
  
  function send_txt_msg($phone, $provider) {
    global $db, $db_user, $db_loc, $db_pass;
    $link = mysql_connect($db_loc, $db_user, $db_pass);
    mysql_select_db($db, $link);
    $query = mysql_query("SELECT * FROM woots ORDER BY id DESC LIMIT 1", $link) or die(mysql_error());
  	$result = mysql_fetch_array($query);
  	
  	$title = trim($result['title']);
  	$price = trim($result['price']);
  	$shipping = $result['shipping'];
  	$shipping = eregi_replace("[[]]+", " ", $shipping);
  	$shipping = trim($shipping);
  	$date = $result['date'];
    
    $to = $phone.'@'.$provider;
    $subject = 'Wootifier.com confirmation message';
    $from = 'admin@wootifier.com';
    
    $message = "Congratulations! Your cell phone is now being wootified! I also sent you today's woot just in case you missed it.\n\n";

    // Send confirmation message
    mail($to, $subject, $message, "From: $from");
    
    // Send Today's Woot
    $subject = "Today's Woot - $date";
    $message = $title."\r".$price."\r".$shipping;
    $message .= "\r\rVisit http://www.wootifier.com to unsubscribe from these messages";
    mail($to, $subject, $message, "From: $from");
    
    @mysql_close($link);
  	@mysql_free_result($result);
  }
  
  function send_email($email) {
    global $db, $db_user, $db_loc, $db_pass;
    $link = mysql_connect($db_loc, $db_user, $db_pass);
    mysql_select_db($db, $link);
    $query = mysql_query("SELECT * FROM woots ORDER BY id DESC LIMIT 1", $link) or die(mysql_error());
  	$result = mysql_fetch_array($query);
  	
  	$title = trim($result['title']);
  	$price = trim($result['price']);
  	$shipping = $result['shipping'];
  	$shipping = eregi_replace("[[]]+", " ", $shipping);
  	$shipping = trim($shipping);
  	$date = $result['date'];
    
    // Send confirmation message
    
    $to = $email;
    $subject = 'Wootifier.com confirmation message';
    $from = 'admin@wootifier.com';
    
    $message = "Congratulations! Your email inbox is now being wootified! I also sent you today's woot just in case you missed it.\n\n";
    
    mail($to, $subject, $message, "From: $from");
    
    // Find woot id on website
    $query = mysql_query("SELECT id FROM woots WHERE title = \"$title\" and date = \"$date\"", $link) or die(mysql_error());
    $result = mysql_fetch_array($query);
    $id = $result['id'];
    
    // Send Today's Woot
    $subject = "Today's Woot - $date";
    $message = $title."\r".$price."\r".$shipping;
    $message .= "\rhttp://www.wootifier.com/archive/#woot$id";
    $message .= "\r\rVisit http://www.wootifier.com to unsubscribe from these messages";
    mail($to, $subject, $message, "From: $from");
    
    @mysql_close($link);
  	@mysql_free_result($result);
  }
  
  function validate_email() {
    global $db, $db_user, $db_loc, $db_pass;
    if (isset($_POST['txtEmail'])) {
      $email = $_POST['txtEmail'];
      $div_error_open = "<div id=\"error\">\n<ul>\n";
      $div_error_close = "</ul>\n</div>\n";
      $valid = false;
      $output = '';
      
      //check if email is valid
      $email_filter="^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$";
      
      if(!empty($email)) {
        if (eregi($email_filter, $email)) { 
          // Connect to database
          $link = mysql_connect($db_loc, $db_user, $db_pass);
          mysql_select_db($db, $link);

          // Run a query to see if email address is taken
          $query = mysql_query("SELECT * FROM emails WHERE email=\"$email\"", $link) or die(mysql_error());

          // Run the query, and put results in an array
      	  $result = mysql_fetch_array($query, MYSQL_ASSOC);
      	  
      	  // If email address is found in database display error
      	  if ($result['email'] == $email) {
      	    $output .= "<li>It appears that your email address is already in the database.</li>\n";
      	  } else {
      	    // Log ip with timestamp
            $client_ip = $_SERVER['REMOTE_ADDR'];
            $query = mysql_query("INSERT INTO ip_entry_dates (ip_address, entry_date) VALUES (\"$client_ip\", NOW())", $link) or die(mysql_error());

            // Check if user has made more than 10 entries today
            $query = mysql_query("SELECT * FROM ip_entry_dates WHERE ip_address = \"$client_ip\" and entry_date > DATE_ADD(NOW(), INTERVAL -1 DAY)") or die (mysql_error());

            $recent_entries = 0;

            // Count the amount of entries in the last 24 hrs
            while (mysql_fetch_array($query, MYSQL_ASSOC)) {
              $recent_entries++;
            }

      	    if ($recent_entries <= 5) {
      	      // Insert email address into database
      	      $query = mysql_query("INSERT INTO emails (email) VALUES(\"$email\")") or die (mysql_error());

      	      // Display succeess message
      	      $output .= "<li>Registration was successful. You should receive a confirmation email message
                      within the next few minutes. If you don't see the confirmation message, check your spam folder!</li>\n";
                      
              $this->send_email($email);
            } else {
              // Show banned message
              $output .= "<li>For security reasons, you are only allowed to submit 5 email and phone entries per day. You have attempted $recent_entries entries within the last 24 hours. Seriously now, do you really need to subscribe $recent_entries times?</li>\n";
            }
      	  }
          
          @mysql_close($link);
        	@mysql_free_result($result);
        	
          return $div_error_open.$output.$div_error_close;
        }
      }
      
      if (trim($_POST['txtEmail']) == '') {
  	    // Display error if field is blank
        $output .= "<li>If you leave the text field field blank, there is really nothing I can do to help.</li>\n";
      } else {
        // Email address entered is invalid
        $output .= "<li>It appears that the email address you have entered is invalid.</li>\n";
      }
      
      @mysql_close($link);
    	@mysql_free_result($result);
    	
      return $div_error_open.$output.$div_error_close;
    }
  }
  
  function validate_phone() {
    global $db, $db_user, $db_loc, $db_pass;
    if(isset($_POST['txtNumber']) || isset($_POST['selCarrier'])) {
      $phone = $_POST['txtNumber'];
      $div_error_open = "<div id=\"error\">\n<ul>\n";
      $div_error_close = "</ul>\n</div>\n";
      $valid = false;
      $output = '';
      $provider = $_POST['selCarrier'];
    
      $phone = preg_replace('/[^0-9]/', '', $phone); # remove non-numbers
    
      //check if number is valid
      if (preg_match('/^1?[0-9]{10}$/', $phone) && $provider != '') {
        $valid = true;
      } elseif (strlen(trim($_POST['txtNumber'])) != '' && strlen($phone) != 10) {
        $output .= "<li>It appears that the number you have entered is invalid.</li>\n";
      }
    
      if ($valid == true) {
        // Connect to database
        $link = mysql_connect($db_loc, $db_user, $db_pass);
        mysql_select_db($db, $link);
      
        // Run a query to see if username is taken
        $query = mysql_query("SELECT * FROM phones WHERE number=\"$phone\"", $link) or die(mysql_error());
      
        // Run the query, and put results in an array
    	  $result = mysql_fetch_array($query, MYSQL_ASSOC);
    	
    	  // If number is not found, continue and insert number into database
    	  if ($result["number"] == '') {
    	    // Log ip with timestamp
          $client_ip = $_SERVER['REMOTE_ADDR'];
          $query = mysql_query("INSERT INTO ip_entry_dates (ip_address, entry_date) VALUES (\"$client_ip\", NOW())", $link) or die(mysql_error());

          // Check if user has made more than 10 entries today
          $query = mysql_query("SELECT * FROM ip_entry_dates WHERE ip_address = \"$client_ip\" and entry_date > DATE_ADD(NOW(), INTERVAL -1 DAY)") or die (mysql_error());
          
          $recent_entries = 0;
          
          // Count the amount of entries in the last 24 hrs
          while (mysql_fetch_array($query, MYSQL_ASSOC)) {
            $recent_entries++;
          }
    	    
    	    if ($recent_entries <= 5) {
    	      // Insert number into database
    	      $query = mysql_query("INSERT INTO phones (number, provider) VALUES(\"$phone\", \"$provider\")") or die (mysql_error());
    	  
    	      // Display succeess message
    	      $output .= "<li>Registration was successful. You should receive a confirmation text message
                    within the next few minutes.</li>\n";
    	    
    	      $this->send_txt_msg($phone, $provider);
          } else {
            // Show banned message
            $output .= "<li>For security reasons, you are only allowed to submit 5 email and phone entries per day. You have attempted $recent_entries entries within the last 24 hours. Seriously now, do you really need to subscribe $recent_entries times?</li>\n";
          }
        }
    	
    	  if ($result['number'] == $phone) {
    	    $output .= "<li>It appears that your number is already in the database.</li>\n";
    	  }
      }
    	
    	// Display error if field is blank
      if (trim($_POST['txtNumber']) == '') {
        $output .= "<li>If you leave the text field field blank, there is really nothing I can do to help.</li>\n";
      }
      
      if ($provider == '') {
        $output .= "<li>Please select a cellular provider.</li>\n";
      }
      
      @mysql_close($link);
    	@mysql_free_result($result);
      
      // Returns error div and message
      return $div_error_open.$output.$div_error_close;
    }
  }
}

?>
What's a better way of doing what I am trying to do?

-Kyle
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

You need a database class. You need to pass an instance of said class to your index controller during creation.
User avatar
pgolovko
Forum Commoner
Posts: 38
Joined: Sun Sep 17, 2006 9:13 am

Post by pgolovko »

I'd just save my config in the database:

Code: Select all

function cfg($v){
	$query = "SELECT `$v` FROM `config` LIMIT 1";
	$result = mysql_query($query);
	echo mysql_error();
	if(mysql_num_rows($result)){
		while($cfg = mysql_fetch_array($result)){
			return $cfg[$v];
			}
		}
	}
and use the values when I need it:

Code: Select all

$bleh = cfg(bleh);
TheProgrammer
Forum Newbie
Posts: 22
Joined: Mon Nov 27, 2006 12:25 am

Post by TheProgrammer »

lol..what these guys are trying to say is that the variable is not visible from withing the function unless is global. so you leave it the way it is where you define it (variables.php), and redeclare it inside the function like this:

Code: Select all

function anyfunction(){
        global $db;
        global $db_user;
        ..........................
        }
Second method is, yes to pass it as a parameter to this function.

Third method is to declare those as constants (this is what they are, i don't see the point of making them variables). Constants are visible inside any scope.

Code: Select all

define("DB_LOC","localhost");
User avatar
ok
Forum Contributor
Posts: 393
Joined: Wed May 31, 2006 9:20 am
Location: The Holy Land

Post by ok »

Simple:

Code: Select all

<?php
class myClassName {
   var $base_dir;
   var $db;
   var $db_user;
   var $db_loc;
   var $db_pass; 
  function myClassName()
  {
     require_once('variables.php');
     $this->base_dir = $base_dir;
     $this->db = $db;
     $this->db_user =$db_user;
     $this->db_loc = $db_loc;
     $this->db_pass =$db_pass; 
  }
  function my_function() {
    echo $this->db; // Throws an error saying it can't find the $db variable
  }
}
?>
kday
Forum Newbie
Posts: 8
Joined: Tue Oct 24, 2006 5:47 pm

Post by kday »

TheProgrammer wrote:lol..what these guys are trying to say is that the variable is not visible from withing the function unless is global. so you leave it the way it is where you define it (variables.php), and redeclare it inside the function like this:

Code: Select all

function anyfunction(){
        global $db;
        global $db_user;
        ..........................
        }
Second method is, yes to pass it as a parameter to this function.

Third method is to declare those as constants (this is what they are, i don't see the point of making them variables). Constants are visible inside any scope.

Code: Select all

define("DB_LOC","localhost");
Thank you all for your help. This is the solution I was looking for.
Post Reply