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




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.




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
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:

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.


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?

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,

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?

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..

Access Class Member Function Without Instantiating Class?
I need to access a class member function from outside the class, and hopefully without having to instantiate the class if possible?

I have an HTML form <select> and each <option> item is being pulled from an array stored in a mysql db.  But I'm doing this independently of the normal purpose of the class itself, I just want to use that member function.

Modify A Function Of A Parent Class From The Child Class ?
How do i modify a function of a parent class from the child class ?

Calling Class Method Of Variable Class.
Yes, it's the week of OO here in c.l.php

If I want to call the method a class (not an object), one normally uses:
classname::method();

which works fine.

However, what if I don't know the classname yet?
$classname::method();
doesn't work, neither does
{$classname}::method();

I've got solved it like this now:
call_user_func(array($classname,'method'));

Syntax? How To Declare A Member Of A Class Which Is Itself A Class
how to declare a member of a class which is itself an object?

class cA
{
private $blah;
public function foo()
{
return blah;
}
}

class cB
{
private cA $a; // I want this to be of type class A
}

DB Connection Handling - I Get "too Many Connection" - What's The Solution?
I have a php-webpage that needs the database in the beginning and in
the end of the script. In the middle there is a lot of processing that
takes several seconds - during that time I don't use the database
connection.

What is the best approach? Should I close the connection after I'm
done with it OR should I reuse the connection thru my whole script?

Where can I read more about this? Any pointers?

Today I'm using the same connection thru my script. And sometimes I
get an error from the database "too many connections". What does that
mean? My webserver provider says that I have at least 100 connections
to play with. How come I get this error?

PHP 4: Does Method_exist Return True If Parent Class Method Even If Child Class Forgot To Call Parent::
My code was dying on the line below where I use method_exists:

if (class_exists($nameOfClassToBeUsed)) {
$object = new $nameOfClassToBeUsed();
$this->arrayOfAllTheObjectsSoFarLoaded[$nameOfClassToBeUsed] = &
$object;
if (method_exists($object, "setCallingCode"))
$object->setCallingCode($nameOfFunctionOrClassCalling);
return $object;
} else {
$this->error("$nameOfClassToBeUsed not found. The code that wants
this class is $nameOfFunctionOrClassCalling ");
}

The method is in the parent class yet I'd forgotten to call parent:: in
the constructor of the child class. It seems to me that method_exists
was testing true, though the method was not truly available, and then
the code died. Adding parent:: to the constructor of the child solved
the problem. Is this a bug in PHP?

Class.phpmailer.php & Class.smtp.php ?
class.phpmailer.php & class.smtp.php ?

Hi friend,

anybody tried class.phpmailer.php & class.smtp.php to
sendmail?

I try to connect to mail.yahoo.com, not working.

<?php
require("class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP();
// set mailer to use SMTP
$mail->Host = "smtp1.example.com;smtp2.example.com";
// specify main and backup server
$mail->SMTPAuth = true; // turn on SMTP
authentication
$mail->Username = "jswan"; // SMTP username
$mail->Password = "secret"; // SMTP password
$mail->From = "from@...";
$mail->FromName = "Mailer";
$mail->AddAddress("josh@...", "Josh Adams");
$mail->AddAddress("ellen@...");
// name is optional
$mail->AddReplyTo("info@...", "Information");
$mail->WordWrap = 50;
// set word wrap to 50 characters
$mail->AddAttachment("/var/tmp/file.tar.gz");
// add attachments
$mail->AddAttachment("/tmp/image.jpg", "new.jpg");
// optional name
$mail->IsHTML(true);
// set email format to HTML
$mail->Subject = "Here is the subject";
$mail->Body = "This is the HTML message body <b>in
bold!</b>";
$mail->AltBody = "This is the body in plain text for
non-HTML mail clients";
if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Message has been sent";
?>

Coding A Class' Function Outside A Class
I still haven't found if there is a way to write functions (methods) that belong to a class, outside of that. Maybe there is not, at least untill now.But I prefered to post a question here about that in case there is and someone knows.

Use External Class In A Static Class
I have a language class with a static method so it can be accesed without instantiation for use all over the shop...

anyway I am using the oop mysqli and wanted to know how to make this available this inside the static method.

Class Inside Another Class 4
I've got a strange situation.
I've got class Handlers it's only:

class Handlers
{
var $DB;
var $XML;
}

In my PHP script I want to do sth like this:

$Main = new Handlers();
$Main->DB = new DataBase();
$Main->XML = new XML();

but when inside eg. CreateNode method in XML class I want to run query
using: $this->DB->RunQuery();
it's of course fatal error...

I saw in one script that such classes
can be created but i don't remember where I found it...

Can it be writen in PHP 4?

Class Inside Class
I'm developing a menu class, and in it, I want to use my sql wrapper, which is also a class. I quickly found out that I'm unable to call a class inside another class. It has been suggested that I tell my menu class to extend my sql class, but it makes no logical sense for a menu to extend a db.

So my question is, are there any other ways to access my sql class's functions inside another class?

Class Can Not Inherit From Another Class, Why ?
I am using this very slightly modified function found here:
http://us2.php.net/mysql_fetch_object
to make mySQL rows into objects of type $classname:

// This takes db result rows and makes real objects of $classname type
function &buildObj($result, $classname) {
while($row = mysql_fetch_assoc($result)) {
if ($row === null) return null;

/* Create the object */
$obj =& new $classname;

/* Explode the array and set the objects's instance data */
foreach($row as $key => $value)
{
$obj->{$key} = $value;
}
$objs[] = $obj;
}
return $objs;
}

This is called by a retrieve: function:

function retrieve($where) {
echo $query = "SELECT * FROM $this->table WHERE " . join(' AND ',
$where);
$result = mysql_query($query);
$rows =& buildObj($result, get_class($this));
mysql_free_result($result);
return $rows;
}

The problem I am encountering is that if I do this in my script:

$listing = new Listing;
$listings = $listing->retrieve(array('row > 1') );
foreach ($listing as $aListing) {
$aListing->address='xxxxxxxxxxxxx'
}
foreach ($listing as $aListing) {
print_r($aListing);
}

The value in $aListing->address is unchanged.

However if I do this:

$listing = new Listing;
$listings = $listing->retrieve(array('row > 1') );
foreach ($listing as $aListing) {
$aListing->address='xxxxxxxxxxxxx'
$newArray[] = $aListing;
}
foreach ($newArray as $aListing) {
print_r($aListing);
}

I see the update values in $aListing->address .


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