PHP - Site Wide Db Connection
Greetings all,
I like to make a config.php file and place it outside my document root for security. I do this all the time. Then just inlcude the config in any file that I need information for. include('../includes/config.php'); This works most of the time for any DB connection information a piece of code might need. However, sometimes I like to place all my functions in a file called functions.php to keep them separate and have a single place to work with them. I have not done any coding in about two years and just started back and for the life of me I can't get any connection attempt inside any of my functions to use the DB connection info from the config.php even if I include the file right inside the functions.php at the top. Even when I put all my functions inside the config file itself they still have no access to the connection vars. I remember that I used to be able to use a global so some type to do this. The important part is getting DB connection access to any functions that I write. Here is an example of a plain config that I might start with; //* Database connection information.. *// $DBHost="localhost"; //* Database Hostname $DBName="some_db"; //* Database Name $DBUser="some_user"; //* Database Username $DBPass="some_pass"; //* Database Password $db = mysql_connect($DBHost, $DBUser, $DBPass); mysql_select_db($DBName); Can someone show me where I'm going wrong and the modern excepted method of doing this? I would greatly appreciated it!! Thank you. Similar TutorialsWhat is the best practice for using site-wide constants in a class? E.g. COMPANY_NAME is set in a config file and used on many pages. How would it be best to use this in a class. I'm guessing just calling COMPANY_NAME anywhere in the class would not be considered best practice. Thanks. This topic has been moved to HTML Help. http://www.phpfreaks.com/forums/index.php?topic=321431.0 I have several "sites" located in my html directory, and each has a "general" access point and an "administrator" access point:
/var/www/html/site1/index.php /var/www/html/site1/administrator/index.php /var/www/html/site2/index.php /var/www/html/site2/administrator/index.php /var/www/html/site3/index.php /var/www/html/site3/administrator/index.phpAll sites are similar except that data will be specific to site1, site2, or site3, etc. Users who log onto /var/www/html/siteX/index.php are totally unrelated to those who logon to /var/www/html/siteX/administrator/index.php, will have different logon credentials, are stored in different DB tables, and each should have their own session. If a user logs off of either the general or administrator site, it should not effect the other site even if they were previously logged on to both on the same PC (and of course not effect other sites). When a user logs off, I would like to destroy their previous cookie and associated session. Users for either will only use https. I am using Apache to rewrite https://www.mysite.com/ to https://mysite.com/. While I named the administrator site "administrator" above, the administrator user has the ability to change the directory name. I am thinking I need to use session_set_cookie_params to specify where I wish the session cookie to be stored since /var/www/html/siteX/administrator/index.php is a sub-directory to /var/www/html/siteX/index.php, but am not really sure. Sorry for the cryptic post, but I am not very well versed in this subject. How would you recommend setting up cookies/sessions for this scenario? Thank you now i use this code to show where the visitors came from to my site. <?php $referer=$_SERVER['HTTP_REFERER']; echo $referer; ?> now, i want to show the 5 latest vistors referer's site url on my site ? Not sure if I'm trying to achieve something totally crazy here, or if this is something pretty standard. Didn't have much luck with searching as I'm not fully down with all the terms. (A) I have one site providing an RSS feed. (B) I have one site I want to search, once for each of the items in the feed A. (C) I want the results of the search in (B) to be displayed on page (C). So for example, the feed on (A) says; apples bananas oranges cheese I want site (B) to search for each of those terms (by passing the item in the feed (A) to the ?search= part of the URL of that page) and then show the results from THAT search on page C. Bit of a complex one, let me know if you need me to clarify. Thanks for any help! Hi, My first post here is a cry for help I have a Windows 2003 server running IIS6/PHP5, the server hosts multiple web sites. The problem is include files that are for site A are showing on site B (each site having its own includes as part of the site files in its own site folder), though not every time, its very random, sometimes the correct includes show, sometimes ones from another site on the same server. This only occurs where the include files for both sites have the same name, such as 'inc-header.php' for example. I can only assume PHP is caching includes and because they have the same name is showing the wrong one on other sites sometimes, if I rename them to something unique then the problem goes away, but its not a practical solution to rename all include files to unique names so I find myself looking for a 'real' fix. I have a feeling its to do with the include_path in the php.ini, but right now its disabled with a semi-colon, and I don't want to set one as I have no global includes, all includes are site specific. Any help would be very much appreciated! Phil HI fellow programmers, Can i connect a textbox to a field in the MySql using the id of the text box? If yes, can u show me a small example. Thanks RAM Hi! I got the following problem... I have a SQL 2005 Server in a VPN. For security reasons,internet access to the database server is only possible for VPN members. Now i want to connect to the openvpn Server from my webserver in order to connect to the database for some webreports. How can i achieve this using php? thanks Hi All, I have a landing page that I use, but often my sql database is too busy or gets overwhelmed and then the landing page just stalls and traffic is lost. Here it is: Code: [Select] <?php //ini_set("display_errors",1); if(!$src) $src = $q; define("__EXEC_", 1); include("config.php"); include("custom.php"); function lsp_visit_find($__val, &$__uid) { global $u; global $db; $l_campaign = array("campaign_id"=>"", "url"=>"", "cost"=>"0.00", "name"=>"-", "ad_keyword"=>"", "mapped_keyword"=>""); $l_visit = array(); $q = $_GET['q']; $src = $_GET['src']; // for STAGE #1 (visit definition): get cost, ad keyword, mapped keyword. $l_campaign['name'] = "info"; $l_campaign['mapped_keyword'] = "$q"; $l_campaign['ad_keyword'] = "$src"; $l_campaign['cost'] = ".02"; // get referer (campaign URL). if no campaign found, - create it! if (!empty($l_campaign['name'])) { $r = mysql_query("select campaign_id,name from campaign where name='$l_campaign[name]'"); if (!mysql_affected_rows($db)) { $r = mysql_query("insert into campaign(name,cost, creation_date,last_update_date) values('$l_campaign[name]',$l_campaign[cost], unix_timestamp(),unix_timestamp())"); $l_campaign['campaign_id'] = mysql_insert_id($db); } else { $w = mysql_fetch_assoc($r); $l_campaign = array_merge($l_campaign,$w); } } // check, whether we had visits from this IP for this keywords within 2 minutes. // if we have one, get its ID, otherwise - create new! $visit_id=""; if (!empty($l_campaign['ad_keyword']) && !empty($l_campaign['mapped_keyword']) ) { $ip = get_real_ip(); $r = mysql_query("select visit_id,uid,campaign_id,ad_keyword,mapped_keyword from visit where ip='$ip' and ad_keyword='$l_campaign[ad_keyword]' and mapped_keyword='$l_campaign[mapped_keyword]' and currtime>=from_unixtime(".(time()-120).") limit 1"); if (!mysql_affected_rows()) { $__uid = md5($ip.time().$l_campaign['campaign_id']); $x = mysql_query("insert into visit(ip,uid,cost,currtime,campaign_id,ad_keyword,mapped_keyword) values('$ip','$__uid',$l_campaign[cost],now(),$l_campaign[campaign_id],'$l_campaign[ad_keyword]','$l_campaign[mapped_keyword]')"); $visit_id = mysql_insert_id($db); } else { $l_visit = mysql_fetch_assoc($r); $visit_id = $l_visit['visit_id']; $__uid = $l_visit['uid']; } return $visit_id; } } $db = mysql_connect(__CFG_HOSTNAME, __CFG_USERNAME, __CFG_PASSWORD); mysql_select_db(__CFG_DATABASE, $db); $u = isset($_GET['u'])? $_GET['u'] : 2; $uid = ""; $visit_id = lsp_visit_find($_REQUEST['l'], $uid); if (!empty($visit_id)) { setcookie("x_uid", base64_encode($visit_id."QQ".$uid), time() + 3600); } global $q; mysql_close($db); $q = $_GET['q']; $src = $_GET['src']; header("Location: http://www.mydomain.com/search/?q=$q"); exit(); ?> My question is how do I code it so that if after 5 seconds or so, or the connection can't be made, it just terminates the connection and auto loads the header redirect at the bottom of the page? Thanks! Hi Guys, need a little help and drawn a blank. The code that is not working is below $result = $conn->query("SELECT * FROM MK_migration_details WHERE mig_bid='".$_SESSION['bid']."'"); I can confirm the $_SESSION['bid'] is working as echo's out on another part of the page. and the above $result works when i manually type the search criteria like below. $result = $conn->query("SELECT * FROM MK_migration_details WHERE mig_bid='300101'"); Basically no result turn up on the page. Any ideas or advise how I can diagnose? Fatal error: Call to undefined function mysql_connect() in C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\connect\index.php on line 10 Hallo I am beginner and starting to learn php I got this message when I want to connect with server. Can I get some suggestion what to do? Thanks I was not expecting this but when I managed to connect to a chatroom and close out firefox.... The user stayed in the chatroom. This user should of pinged out by now but it's staying online. How do I end this connection? So far I turned off my internet, and blocked all access to the site. I'm looking to connect to a MySQL localhost on my mac. I've been working for a few hours at this and I still can't figure it out. Below is my code. I've tried a number of different ways to connect to the database including using new mysqli, mysql_connect and PEAR MDB2. Any suggestions as to what I can do? Thanks in advance. <?php $first=$_POST['first']; $last=$_POST['last']; if (!$first || !$last) { echo 'Error: Enter the required data.'; exit; } if (!get_magic_quotes_gpc()) { $first = addslashes($first); $last = addslashes($last); } $hostname = 'localhost:8889'; $username = 'root'; $password = 'root'; $dbname = 'phonebook'; @ $db = new mysqli($hostname,$username.$password,$dbname); if (mysqli_connect_errno()) { echo 'Errer: Could not connect to database'; exit; } echo '.....Connected Successfuly'; $query = "insert into contact values ('null','".$first."','".$last."')"; $result = $db->query($query); if ($result) { echo $db->affected_rows." contact inserted into the database"; echo 'Contact Entered: '.$first.' '.$last.''; } else { echo 'Error: Contact not added.'; exit; } $db->close(); ?> Hi, Cannot put this together... what link do I use for my website to bring up the contents? The database is good, all the stuff is there.
I did this... https://www.cloudways.com/blog/connect-mysql-with-php/#createfolder *********************** <?php function OpenCon() { $dbhost = "localhost"; $dbuser = "root"; $dbpass = "1234"; $db = "example"; etc.,etc. *********************** <?php /* Setup MySQL Access */
$DBhost = "localhost"; ?>(not uploaded, wanted to ask first - HTML page with above php inside?)
(config) <?php error_reporting(0);
// db bits here
// site details
// other bits
//DO NOT MODIFY THE LINE BELOW
?> Leo Duchaine (php wannabe)
Is there a way to instantiate a PDO object using an already existing database connection? Or does PDO detect an already opened connection and use it? The existing connection is a persistant connection. Hi, I'm trying to write my first MVC framework for my college project and faced this problem: i have main framework class, and have this loader class, that loads view files and libraries. Now, how can I do that when I load library, I could reach it from my main class? For example: in main class goes this code: Code: [Select] public $load; function __construct ( ) { $this->load = new Loader; } function someFunction ( ) { $this->load->library('someLibrary'); // and now reach the library like this $this->someLibrary->functionInLibrary(); } The idea is from codeigniter, so if anyone has used this framework will understand my question. <?php class UserQuery { public function Adduser($id,$username,$email,$password) { $conn = new Config(); $sql =("INSERT INTO test.user (id, username, email, password) VALUES ('$id', '$username', '$email',$password)"); $conn->exec($sql); } }
getting an "exec doesnt exist " error, saying exec doesnt exist in my db file. it doesnt need to exist does it ? anyone any idea why ?
hi everyone I have a question... does creating a connection to mysql takes time depeding on the database size? Lets say that in my entire project I will be connection to 4 databases so I created a config.php which looks like this: Code: [Select] $hostname = "localhost"; $username = "root"; $pword = ""; $con1 = @mysql_connect($hostname,$username,$pword,true); @mysql_selectdb("databasename1",$con1); $con2 = @mysql_connect($hostname,$username,$pword,true); @mysql_selectdb("databasename2",$con2); $con3 = @mysql_connect($hostname,$username,$pword,true); @mysql_selectdb("databasename3",$con3); $con4 = @mysql_connect($hostname,$username,$pword,true); @mysql_selectdb("databasename4",$con4); so, this file is included in every pages, I put this on the top. Basically every page request it will open 4 connection and the script will only use 2 connection and another page will only 1 and so on..... this style is very convenient as for I am not creating a connection in every page.. But my concern is will it effect the performance of my system? Tnx in advance..... I have an app that connects to a source safe server to perform a command via shell_exec(). I had used exec(), but shell_exec seems to work better since I am on Linux. The command connects to the server and tells it to promote a file to the next level. On Windows this ran without a hitch, but on Linux I gat an error that reads: Quote Socket error when reading request from [172.20.22.1]: 3537808 ; Socket closed. I am told that the reason for this error is that PHP broke the connection to the server before the server completed the job and was able to shutdown properly. The only way I have found around this is to place a sleep(3) to the script. This is really not ideal since that means that there is at least 3 seconds between each command, which can really extend the time it takes to perform if there are numerous files. If PHP breaks the connection before the program can close it will leave the program open and PHP cannot perform any more commands to the server since it is stuck on the last command. If too many are given the machine will lock up due to resources being eaten up. I'm wanting to know if there is a way to tell PHP to not let go of a connection so quickly. I tried "nohup", but that does not help. I am new to Linux and am at a loss of what my options are beyond the sleep() method. I really feel that there has to be a better way or setting that can be manipulated to fix this issue altogether. Thanks in advance for any help. Cy It seems that a class can't inherit an object as attribute? I'm trying to make my UpperNavigation class access the $this -> db attribute which is a mysqli connection. Is this possible? If not, how do I manage my connection in other classes? Code: [Select] class Connection{ public $state = false; public $db; public $db_table_names; function __construct($name){ include('dbconfig.php'); $this -> db = new mysqli($dbconfig[$name]['server'], $dbconfig[$name]['username'], $dbconfig[$name]['password'], $dbconfig[$name]['database']); $this -> state = true; $this -> db_table_names = $db_table_names; $this -> db -> query("SET NAMES 'UTF8'"); } function close(){ if($this -> state == true){ $this -> state = false; $this -> db -> close(); unset($this -> db); } } } This is my attempt of accessing Connection::$db connection. Code: [Select] class UpperNavigation extends Connection{ public $all_parents_sorted; public function printUpperNavigation(){ echo '<a href=\''.$this -> current_page.'\'>'.$this -> title . '</a>'; } public function printSearchBar(){ echo '<input type=\'text\' value=\'Search by name...\' onfocus="if(this.value == \'Search by name...\'){this.value = \'\';}" onblur="if(this.value == \'\'){this.value = \'Search by name...\';}"/>'; } public function fetchAllParents($sp_id){ $latest_id = $sp_id; if(isset($this -> db)){ echo 'yes'; }else{ echo 'no'; } $query = 'SELECT default_name, type, sp_id FROM ' . $this -> db_table_names['sport'] . ' WHERE sp_id = "' . $sp_id . '"'; $result = $this -> db -> query($query); // THIS IS THE PROBLEM } } |