Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
 
  HOME    TRACKER    PHP




Database Class: Closing Connection


I am just learning OOP in PHP and I decided making a DB class would be a good start for my first real type of OOP class. Everything is working fine but I am having problem's closing the connection. I was wondering if anyone can see what the problem might be if it is in the coding. database.class.php PHP Code:




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
Closing A Database Connection
for my php site, i open a mysql connection for each page cause most of my pages uses some data from the database. however, i did not close the mysql connection - will this have any bad effect to my database? or is it better to have all connection closed once my php script is finished?

Class For Database Connection
Can anyone tell How to write class for database connection in PHP . Class must provide a general function for executing queries.

PHP Class Connection
I keep getting a:

mysql_fetch_array(): supplied argument is not a valid MySQL...

this is my class connection

<?php

class cDatabase {

//class variables defined in constructor
var $host;
var $user;
var $password;
var $databaseName;

//constructor - needed for connection string
function cDatabase($hostName, $userName, $passwordName,
$databaseName){
$this->host = $hostName;
$this->user = $userName;
$this->password = $passwordName;
$this->database = $databaseName;
}

//execute a query
function ExecuteNonQuery($sql){
$conn = mysql_connect($this->host, $this->user, $this->password);
mysql_select_db ($this->database);

$rs = @mysql_query($sql);
settype($rs, "null");
mysql_close($conn);
}

}

?>

and this is the page

<?php

include "dbclass.php";

$cDB = new cDatabase(host, user, password, database);

// test select query
$rs = $cDB->ExecuteNonQuery("Select event from na_events");

while ($row = mysql_fetch_array($rs, MYSQL_ASSOC)) {
echo $row['event'];
}

// kill our objects
settype($rs, "null");
settype($cDB, "null");

?>

Database Connection ?
I am very new to PHP...Can i get the starting code for connecting to database....how to open the connection...what is the connectionstring ?

Database Connection
<?php

I have a question about 2 connection strings to a ms sql database.

# TEST DATABASE

$connecttest = MSSQL_CONNECT("TEST", "sa", "123456") or exit("Unable to
connect to MS SQL Server at 10.0.10.58");

$select = mssql_select_db ("database1",$connecttest) or exit("Unable to
select database TEST");

# PRODUCTION DATABASE

$connectprod = MSSQL_CONNECT("PROD", "sa", "654321") or exit("Unable to
connect to database at 10.0.10.59");

$select = mssql_select_db ("database2",$connectprod) or exit("Unable to
select database PROD");

$SQL = "SELECT * FROM table1";

$RESULT = mssql_query($SQL);

// What data will i find here? Is it data from the TEST or from PROD and
will it be data from database1 or from database 2?

?>

Connection To Database
Running RH8 and have installed mysql, apache, php. I have pypmyadmin working fine, adding and editing databases.. but when I try to get a form (to enter data) its does not connect or just sumbits as if all was ok but nothing happend.

Database Connection Limits?
I am in big confusion right now plz tell me one thing with explaination.

Situation is:

I have a script in that i am using database connection and some database operation. 10 users are accessing this script same time.

what happen is there 10 connection to database sever or there will be only one connection?? if there would be 10 connections then what is the max limit of mysql.


Database Connection Problems?
I am all new to php/mysql and was wondering if someone might help me
out on a little problem that I am having.
It must be something very simple that I am missing, it seems that I am
having trouble connecting to the database, yet all of my information
seems to be correct - the error is as follows:

Parse error: parse error in
/data/members/free/tripod/uk/t/h/e/theresearcher/htdocs/scripts/conf.inc.php
on line 6
the error repeats twice.

Line 6 in my conf.inc.php states:
$mysql_database='theresearcher_uk_db'

I have enabled both php and mysql twice just to be sure. Hostname
localhost is correct. Double checked the database name. No password is
required so i left it blank. (should I take the line out alltogether?)
I dont know what to do about the port..lycos didnt say anything about
it so I left it blank. The table prefix I am not sure of either.

Here is the surrounding code:
$mysql_hostname='localhost'
$mysql_port=''
$mysql_user='theresearcher'
$mysql_password=''
$mysql_database='theresearcher_uk_db'
$mysql_table_prefix=''
$mysql_pconnect="NO";
$pages_dir='/data/members/free/tripod/uk/t/h/e/theresearcher/htdocs/'
$pages_url='http://members.lycos.co.uk/theresearcher/pages/'
$scripts_dir='/data/members/free/tripod/uk/t/h/e/theresearcher/htdocs/;
$scripts_url='http://members.lycos.co.uk/theresearcher/scripts/'

Connection To Database Or Die Message
When connection to the database fails I would like to include an email link in the response message, but I need help with how it can be done.  Below is my code and I want the error message text to include a Report This email html link. Code:

Php Mysql Database Connection
i want to add my form details to the mysql database. i had done it with mysql_connect('localhost','root',''); but the error was localhost connection failed. Code:

PHP MySQL Database Connection
I'm involved in a project where I have to create a web application with PHP and MySQL. My question is, usually we use one user name and password to connect to the database for the whole application, in which case all the users will connect to the database with that username we set in PHP script.

If we want to have different users with various access rights on the database this strategy will not work, because we give one username and give maximum access rights for that username. Is there any way where you can define the access rights of a user in the database(MySQL) and use the same username and password when the user connects to database through PHP application?

If so, we will have hundreds of users connecting through the PHP application with different usernames and password, will this have any impact on the web server or DB server? Is it secure? Is there any other way this can be done?

PHP/MySQL Database Connection Problem
when I'm doing an insert (using mysql database) it produces the following two error messages :

Warning: MySQL: Unable to save result set in [file].

Lost connection to MySQL server during query

These errors occur after the number of conncections increases, before this there is'nt any problem.

I am using PHP 4 with Apache on Redhat Linux 6.2.

How To Make A Database Connection Available To All Pages?
How can I make a database connection available to all the pages in my
application? I tried doing it with session but it doesn't seem to work.

here's what a did:

What Is Going Wrong In The Database Connection With PHP MYSql
I am setting up a site for a client that requires signup and
login. I have written most fo the code but, for some reason am
have trouble with the database connection. The problem is with
the connection. I believe I have the right server but, have had
trouble getting the correct iser and password. Is there a way to
determine what is going wrong in the connection because
setting up die with a message doesn't tell me anything other
than the connection failed. I going back to client and getting the
support # from yahoo who set up the server and database.

Hopefully I can talk to the person who set up the server for him
and get the proper server, user and password. It would be nice
to know how to troubleshoot the connection in a more
meaningful way.

No Luck Making A Database Connection
I've included db.php into my script, and this is all it contains:

$host = 'localhost'
$username = '***'
$password = '***'
$database = '***'
$connection = mysql_pconnect($host, $username, $password);
$mysql_select_db($database, $connection);

obviously with the other fields filled out.

My webhost tells me to use this script:

$dbh=mysql_connect ("localhost", "<USERNAME HERE>", "<PASSWORD HERE>") or
die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db ("<TABLE NAME>");

neither one of these methods work, actually - I get this error:
[the contents of my db.php file here, in plain text!]No Database Selected

Hiding Database Connection Info
In a php script, I have to connect to a remote mysql database. I'm a bit
worried that some user might be bale to retrieve the source of the page and
see the user name and password to connect to the db.

Is this resonable? What's the best way to avoid it?

ADODB Multiple Database Connection
I'm using ADODB for a PHP project and am having problems with multiple (MySQL) databases. I've looked through all the docs and am stumped. I know how to use PHP and MySQL and I still haven't got a clue why this isn't working. Code:

How Do I Connect To A .mdb (access) Database With A Dsn-less Connection Using Php4?
I need to connect to an Access database without a dsn. Can you give me an example (a simple table display with a while !rs->eof)

Using Global Variables In The Database Connection String
I'm sure this has been asked a million times but I can't seem to
formulate a google search that returns what i'm looking for.

I've go a dev and live environment. Currently the DB connect string is
hard coded into each php file which means i'm going to have to change
every page - Arrgh!!

If i put the DBonnect into a function and store it in an include file,
it doesn't seem to work, Also the connetion works with inline PHP
statements, but I have to repeat it in every function even if they are
in the main php file??? which doesn't seem right to me..

I need to either :-

Store the connection variables in an include file and retrieve them as
global values

OR

Store the connection string in a function in an include file which can
be accessed by all functions.

also do I really have to call the dbconnect inside every function.

Please note, if it makes any difference, I still havn't got my head
round OO programming in PHP so it is still pretty much procedural. I
am using PEAR but dont really understand (or care at the moment) about
what it is doing.

Connect To Foxpro 2.6 DOS Database Using Php Odbc Connection.
The driver that I use in ODBC Data Source Administrator is Microsoft dBase Driver (*.dbf). Is it correct. Code:

Database Class Within A Other Class
I’m rewriting a script of mine into PHP5 OOP. Even tho I have some difficults finding a good way. I have a Class for database connections/functions (clsDB) and a Class for Statistics (clsStats) So my question is, what’s the best way to use the DB functions within the Stats class? Code:

Errors - Putty.exe (telent Connection To Mysql Database)
The following code produces an error when I try to run it under
putty.exe (telent connection to mysql database). Can anyone identify
the error in the code? The server is running PHP5.


DELIMITER ;;
/*!50003 DROP PROCEDURE IF EXISTS `aaa` */;;
/*!50003 SET SESSION
SQL_MODE="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER"*/;;
/*!50003 CREATE PROCEDURE `aaa`()
begin
declare iTest int;
set iTest = 5;
end */;;

Check If Database Exists Even If Connection Credentials Are Incorrect..
How can I check if database exists even if the connection credentials are incorrect?

Database Connection Problem In Included File On Root Directory
I have a file called tophtml.php that connects to the database. It's in the root directory of the site. It works perfect in the root directory. But if I call it in a sub directory. (e.g. require("../tophtml.php") or require("C:websitesdogrealm ophtml.php")) I get errors saying it can't connect to the database.

Database Class
I just made a database class that connects to mysql and does query, connect and various other database operations. Now i made an instance of this class in my main page am able to use it without a problem. But now i am having trouble when i am trying to use this object when i open another page.

I want to be able to use the same instance from the main page so i need some way of passing it from one page to another. I can probably get around this problem by just making another instance of this class and making another connection to the database, but i would like to do it without making multiple connections if i can. Any suggestions?

Abstracting A Database Class
I've been using PHP for a while and I'm hearing that I should look into
using it OO. I'm looking into making changes to the program Camera Life
(http://fdcl.sf.net). I want to abstract the connection to the database
which is currently MYSQL and maybe implement another database, or just
leave it open for addition. If I get lucky and get the hang of this,
I'd also like to abstract calls to GD.

So firstly, is there a good solution to this problem? I've seen many
examples, but many of them are incomplete or simply academic. Also,
will I lose any functionality by doing it this way? I am currently
using a complicated SELECT statement with a CONCAT. Will this be
possible with the abstracted class?

Database/SQL Abstraction Class
I am currently writing an application that I want to work on multiple database systems. However I am not sure what is the best way to abstract (factor out) the database code from my main application code.

Currently I use ADOdbLite to abstract myself from the different db APIs used however this does not protect me from the different variants of SQL used. How would you suggest I do this.

Some people have told me to write a DB class that contains all of the queries wrapped in functions, such as getUserInfo($userID). Does this seem like good design practice, and if so how much work would you suggest the functions/methods do, should they just run the query of return the result set or also process it into something like an array?

Database Query From Within A Class Function
My application is object orientated and each object requires a cooresponding "PageID" in the tables "Page" and "PageContent" as well as a few other necessary elements to display properly as a web page.

Some page elements are contained in their own tables, but are associated with the"Page" and "PageContent" tables by the "PageID" that cooresponds to the page the element should be displayed on.

I have written a script that allows me to create a new page by inserting data into fields on the "Page" and "PageContent" tables, but it only works as long as the "PageID" in each table is auto_incrementing in sinc.

I wanted include a method for members to sign-up for the site and I fould a script named "Authlib v1.94" that seems to work pretty well on its own. However, I hacked the code to redirect the data to an existing member table and cut out some of the validation. My intital tests on the hack have been satisfactory.

If any of you are familiar with the "Authlib v1.94" code you may be aware there's a file named backend.php included in the script. It is a class file that includes some pretty nice validation functions for dealing with registering new members, logins, etc.

The register function of the authlib class validates user input from the regestration form. If all the checks pass, it goes on to create a new entry in the "Member" table. (Keep in mind that I redirected the data to this table and hacked the code a bit.) The code looks something like this: PHP Code:

Simplifying Repeating Database Connections In A Class?
I wrote my first PHP class today. Yeah!
But to get it to work, in each function within the class I have to
repeat the database connection lines, and that just seems redundant;
there has to be a better way that I'm just not bright enough to think
of.

(It's the first 3 lines of each of the two functions below. When I have
it fully written, there will be about 10 similar functions, each
repeating those three lines.)

class e_test {

function gettech() {
include('../Connections/userDBconnect.php');
$db = mysql_select_db("printing", $connection) or $error .= "Could
not select database1: " . mysql_error()."<p />";
$dbconn = $connection;
// CREATE TECH ARRAY
$sql_T = "SELECT email FROM tbl_users WHERE dept = &#391;' AND
active=&#391;'";
$result_T = @mysql_query($sql_T, $dbconn) or $error .= "Could not
query1: " . mysql_error()."<p />";
$count_T = mysql_num_rows($result_T) or $error .= "Could not select
query2: " . mysql_error()."<p />";
$i_T = 0;
while ($row_T = mysql_fetch_array($result_T)) {
$email_T = $row_T[email];
$techs .= $email_T;
$i_T++;
if ($i_T < $count_T) {
$techs .= ",";
}
}
echo $error;
return $techs;
}

Creating A Search Class That Searches Any Database
I've been requested by a client to implement a search engine on it's website. I told him that he does not need it, but he thundered on and well...Who cares, he' s gonna pay for it.

I've made search methods for other sites, but I would like to implement a portable one. A Search Class that could work for any DataBase and with ease of configuration.

Maybe de constructor could receive a database name in which to search.

And the function search, could receive an array of tables in which to search on and a string to search for on those tables. The question is...how would u implement the way that the class returns results?

Nowadays any pro site has the MVC controller. That means that almost all tables in the database have its corresponding model.  Table clientes correspond to the Client Model. How would you implement the results return?

Looking For Independent Database Class That Supports All Major Databases
I guess the title says all.

I'm looking for independent database class that supports all major databases.

I ran across this in the past, but now that I need it I can't find it. It is a class that allows a programmer to select which database the program will access. It is built so that a script can be portable without write to database functions.

Database Class Allowing Saving Data To (XML?) File
I'm looking for a PHP database class which allows database connections
to mysql, AND (text/XML) files to store information.

I'm looking to use the file storage in a small intranet usage of my
programming, and the database (mysql) storage in an online (internet)
site.

If anyone knows of any open-source PHP code for this,

Closing Connections?
I know alot of people are probably getting tired of the mysq_(p)connect questions, but I could not find an answer anywhere else.

If I run multiple queries in a page and parse HTML inbetween them, should I close the connections inbetween the queries (using mysql_connect()) or should I just let it be until the script is finished?

Closing Databases
I am using mysql_connect($host,$user,$db_password); to open a mySQL database. Do I need to be closing the database manually after working with it on the page or does php automatically take care of this ?

Closing Window
Here is a problem I encounter often but haven't solved.

In a form I have a submit button. When clicked, I want to do some processing
so I check with the isset($_POST['the_button_name']). (I keep all my code
above the html code). Now, once I have done that processing, I want the
window to disappear. Is it as simple as adding an on_click event to close
the window? Will the processing then still take place?

PHP.exe Closing On Exit
Is there any way to stop php.exe closing after it processes a PHP script? It
doesn't seem to have the traditional options of an MS-DOS program. I am
using Windows XP Pro and have associated .php files to open with
C:PHPphp.exe -q %1.

Closing A PHP Script Properly
Hi

I'm using a PHP script with socket connections to transfer data between the browser and an application. It uses server push to display the data, so this means that the connection stays open as long as the user doesn't press the Stop button. However, when the user aborts the data stream (i.e. pushing the browser's Stop button), the socket server still thinks the connection is open and keeps sending data, which causes the server socket application to crash. I know there have to be techniques to prevent the crash on the server side, but I was
wondering if there is a way to make a script send "a last command" before the connection is actually broken (in my case, the fclose command)?

Thanks

Opening/closing Tags
Does it matter if you do this, i mean does the preformance suffer when you do this too often? PHP Code:

Logout On Closing Browser
How can I run a logout script when a user close the browser. This is for a login/registratin system, to change a flag in teh database from "online" to "offline" if user closes the browser without loging out.

How Do I Hide Database Connection Files Using PHP Include Files?
I have the following at the beginning of the PHP page:

<?php require_once('Connections/conn.php'); ?>

I want to hide the connection file, "conn.php", so it's out of the web
accessible file structure. I understand putting them in the php include
directory shoudl do this. For example, let's say the directory I put them
in is /www/phpIN/, and /www/ht/ is the root web directory.

So I put "conn.php" in the inlcude directory (/www/phpIN/conn.php) and
removed it form CONNECTIONS directory.

How Do I Hide Database Connection Files Using PHP Include Files?
I have the following at the beginning of the PHP page:

<?php require_once('Connections/conn.php'); ?>

I want to hide the connection file, "conn.php", so it's out of the web
accessible file structure. I understand putting them in the php include
directory shoudl do this. For example, let's say the directory I put them
in is /www/phpIN/, and /www/ht/ is the root web directory.

So I put "conn.php" in the inlcude directory (/www/phpIN/conn.php) and
removed it form CONNECTIONS directory.

Now it doesn't work.

What do I need to change?

Closing Session For Good On Logout
I am trying to ensure the session itself is killed on my logout procedure.

This is a segment from the end of my logout.php:

if (isset($_COOKIE[session_name()])) {
    setcookie(session_name(), '', time()-42000, '/');}

session_destroy();
header("Location: goodbye.php");

Basically, after the user has logged out, I want the session id to be deleted.  The script then refers them to goodbye.php.  goodbye.php has a hyperlink back to the login page.

The problem is, when I click the hyperlink which takes me back to the login page, I still see the same session id (when i output the session info).  My goodbye.php script does not have session_start() in it anywhere.

Does anyone know if I am doing something wrong above?

A Closing Echo In Include() File?
Is it somehow possible to include() a .php file in a php document when the php file is something like this:

<td></td>';
echo ' <td>...

In other words, to include a php file that has a closing and starting echo. How could I do that?

General Question About Sessions Being Sticky And Closing Properly
I have some complex scripts that work fine. I have a system where sessions are validated on every
page of my application to keep them secure. Everything runs fine when I test and code things. But I
am also fanatical about updating the browser for security patches and remove all spyware, virues
etc.. But some of my clients are not that savy and that leads me to my first question.

Occasionally I have a client complain that when they are filling in a long form by the time they get
to submit they've lost their session connection and are forced to log in again and start over.

I can maintain a session connection for a long time and can't figure out why some people get booted
off and some don't. it's randon can't find a pattern. I suspect it has something to do with browser
refresh or popups or whatever... Anyway I'm looking for ideas how to maintain or increase
"stickyness" with sessions?

Second question. When clients use my application I do provide links they can use to "log out" but
what happens to sessions when they just close the browser without logging out first? The system
seems to operate fine, but should I be concerned or not? Is there some method to clear away old
session data when the browser is just shut down without the client loggin off correctly, or should I

Performance Issues With Frequently Closing/opening Mysql Connections?
I have been faced a couple of times with the situation that I wanted to
write a script and was worried about a too frequent opening and closing
mysql connections.

To give some examples:

1)I am trying to develop a photoalbum (also posted a topic called "array /
mysql question"). Of course I can use some wonderful open source albums but
at the same time I want to get more familiar with all the ins and outs so my
idea is a list of filenames, where the database connection should be
opened, a statement like"select filenames from photos" , and, every filename
maybe with a thumbnail is a link to a second page and the whole is followed
by closing the connection. The second page could be something like opening
the database connection, a statement like "select description ( and other
fields) from photos where filename = $filename" , and closing the database
again. Let's say the visitor looks at the picture and its description,
clicks on a link to the first page with the thumbnails and agin the
connection is opened and closed to execute the first select statement, the
visitor chooses another picture etc. etc....

2)On the left column there is a menu item
"activiteiten". when there are special activities like a music performancein
the near future they are shown below that menu item. A select statement is
done where the first announcement date, and the last announcement date are
checked and the records where the current date is between those values are
selected (and shown in the menu bar of course). Again the connection is
opened and closed again immediately after the select statement. However,
this query is stored in "header.php" so on every page that is visited, the
connection is opened and closed. It would also be nice to make a link on the
"one-photo-page" to the previous and the next photo, which leads again to
the open-select-close "ritual".

I am not really a php guru (but not a newbie either) and unfortunately I
could not find many info on google about the performance issues that can be
involved when I decide to write such scripts. There were some vague
indications that it is better to open and close a connection frequently than
leave it open too long in order to execute more queries but I could not
really find good documentation about it.

I also thought to store the results of the query into a session variable but
I am not sure about the performance issues of sessions either.

Bold, Italics, Underline Str_replac'd Using The Same Char For Opening And Closing Tags
I want to write a _very_ simple text parser that would replace a
string like:

"This is text with /italics/, *bold* and _underline_."

and generate automatically something like this:

"This is text with <i>italics</i>, <b>bold</b> and <span
class="underline">underline</span>."

I've found a lot of code snippets explaining how to do BBCode, but
BBCode has different opening and closing pseudo-tags. In my example,
the opening and closing tags are the same (either /, * or _). So I
need something slightly more intelligent that would count the number
of /, * or _ tags, see if that number is even or odd and decide
accordingly if it must replace the char with an opening or closing
tag. (I hope my wording makes sense. It's very clear in my head :-D)

How would you implement that? I reckon it can't be hard, but I just
can't figure how to do it right now!

Defining A Class/instantiating Object Inside A Method Of Another Class
I have a class. Inside the class I have a method that reads a text file.
In the text file I have a class name and a file name where that class is
defined. Now, I need to instantiate an object of that class, the problem
being that at the time I find out the class name and the file name, I'm
inside a method of another class. Well, let me just type up a little
example:

Child Class Member's Iteration By Parent Class
I have a class that has a few private members. Is there a way to create a function in its parent class that can access its (child's) private members.

With the following code I am able to get only the public and protected members.

class parentIter {

function iterateProps ( ) {
foreach ( $this as $propName => $propValue ) {
echo "<br>$propName => $propValue" ;
}
}
}

class childIter extends parentIter {
protected $var1 = 'protected var' ;
private $var2 = 'private var' ;
public $var3 = 'public var' ;

function iterateProps ( ) {
parent::iterateProps () ;
}
}
$obj = new childIter () ;
$obj->iterateProps ( ) ;

PHP5: Can A Class Inherit Initialized Classvariable From Another Class?
I got following problem trying to inherit a variable from another class

class Core
{
public $obj;

function initialize($obj)
{
$this->obj = $obj;
}

}

class test extends Core
{
function test()
{
echo $this->obj;
// or
echo parent::$obj;
// ??
}

}

$core = new Core
$core->initialize('hello');

$test = new test
$test->test();

As far as what I would like to get, I would see 'hello', but instead I
get following error:
Fatal error: Access to undeclared static property: Core::$obj (echo
parent::$obj;)
After declaring $obj as public and static I don't get any result as
well..
Is it possible to inherit already initialized variables from a
different class or are there design patterns who could do something
like that? I hope it is clear where I want to go with this..
I am doing this because I can't give the class test any parameters
because it could be extended (class woow extends test). Also the amount
of variables is not certain and there might be lots of classes needing
to inherit the variables. That would mean that I would have to change
every class if a parameter would change..


Copyright © 2005-08 www.BigResource.com, All rights reserved