Jump to content


Photo

Introduction To PHP Classes OOP


  • Please log in to reply
23 replies to this topic

#1 famous58

famous58
  • Members
  • PipPip
  • Member
  • 21 posts

Posted 18 May 2006 - 05:11 PM

OK. So I am trying to teach myself PHP Classes. I'm trying to create a MySQL connection and query the DB and echo a result. It's not working.

Here's what I have:
mysqldb.php
<?php

class MySQLConnect{
    var $connection;
    
    function MySQLConnect(){
        $dbhost = "localhost";
        $dbuser = "dbuser";
        $dbpass = "dbpass";
        $dbname = "prellisp_printing";
        
        $this->connection = mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error());
        mysql_select_db($dbname, $this->connection) or die(mysql_error());         
        }
    
    function GetUserInfo() {
    $query = "SELECT * users WHERE username=admin";
    $result = mysql_query($query, $this->connection);
    $row = mysql_fetch_array($result);
        }
    
    }
?>

mysqldb_echo.php
<?

include('mysqldb.php');

$output = new MySQLConnect();

?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body>
<? echo $output; ?>
</body>
</html>

What I get is "Object". I've looked at the OPP tutorial on this site and at webmonkey, but neither show what I'm looking for. I want to be able to display any section of data, i.e. username, email address, etc.

Any help is appreciated.

Mod Edit(shoz): connection details removed
I'm trying, really I am.

#2 ober

ober
  • Staff Alumni
  • Advanced Member
  • 5,337 posts
  • LocationEast Coast, USA

Posted 18 May 2006 - 05:19 PM

And that's exactly what you should be getting. All you've done is create the object and run the constructor.

You need to do something like this:
$cn = new MySQLConnect();
$cn->GetUserInfo();

But that's not going to output anything either, because you don't actually spit out your results, unless you're not showing us everything.

Info: PHP Manual


#3 famous58

famous58
  • Members
  • PipPip
  • Member
  • 21 posts

Posted 18 May 2006 - 05:33 PM

[!--quoteo(post=374988:date=May 18 2006, 09:19 AM:name=ober)--][div class=\'quotetop\']QUOTE(ober @ May 18 2006, 09:19 AM) View Post[/div][div class=\'quotemain\'][!--quotec--]
And that's exactly what you should be getting. All you've done is create the object and run the constructor.

You need to do something like this:
$cn = new MySQLConnect();
$cn->GetUserInfo();

But that's not going to output anything either, because you don't actually spit out your results, unless you're not showing us everything.
[/quote]


Thanks for the superfast reply.

I guess that's what I'm asking. How do I output the results? Up until now I've been doing things like:

$link = mysql_connect(DB_SERVER, DB_USER, DB_PASS) or die(mysql_error());
$q = "SELECT * FROM products WHERE `id`=$id";
$result = mysql_db_query(DB_NAME, $q, $link) or die(mysql_error());
$row = mysql_fetch_array($result);

echo "User: " . $row[username] . "<br>";
echo "Email: " . $row[email] . "<br>";

or

while($row = mysql_fetch_array($result)) {
echo "User: " . $row[username] . "<br>";
echo "Email: " . $row[email] . "<br>";
}

But now I'd like to take it to the next level. I'm getting into things like shopping carts and sessions and it seems like my little thrown together sql statements won't cut it any more.
I'm trying, really I am.

#4 ober

ober
  • Staff Alumni
  • Advanced Member
  • 5,337 posts
  • LocationEast Coast, USA

Posted 18 May 2006 - 05:38 PM

I think you're confused or I'm not catching on to what you're trying to do. I assume "getuserinfo()" is always going to have the same output.... so you would put the echos and whatnot in the class as well. Keep in mind that calls to functions in a class can work somewhat like a more powerful include().

When you call the $cn->GetUserInfo() and you have your while loop and echos in the class, it will display all that information for you. You don't have to return it or anything like that.

Info: PHP Manual


#5 famous58

famous58
  • Members
  • PipPip
  • Member
  • 21 posts

Posted 18 May 2006 - 05:52 PM

[!--quoteo(post=375002:date=May 18 2006, 09:38 AM:name=ober)--][div class=\'quotetop\']QUOTE(ober @ May 18 2006, 09:38 AM) View Post[/div][div class=\'quotemain\'][!--quotec--]
I think you're confused or I'm not catching on to what you're trying to do. I assume "getuserinfo()" is always going to have the same output.... so you would put the echos and whatnot in the class as well. Keep in mind that calls to functions in a class can work somewhat like a more powerful include().

When you call the $cn->GetUserInfo() and you have your while loop and echos in the class, it will display all that information for you. You don't have to return it or anything like that.
[/quote]

Ahhhh.

I was trying to build a connection class that I could use accross the board then grab the info. I see now, I'd have to put the echo's in the function.

One more question, and if it's too complicated nevermind, but what if I want the info to be based on a variable, i.e.:

function GetUserInfo() {
    $query = "SELECT * users WHERE username=$user";
    $result = mysql_query($query, $this->connection);
    $row = mysql_fetch_array($result);
        }

It seems that if $user is being defined on mysqldb_echo.php, then it won't work. Would something like $cn->GetUserInfo($user='admin'); tell the function what $user is?
I'm trying, really I am.

#6 ober

ober
  • Staff Alumni
  • Advanced Member
  • 5,337 posts
  • LocationEast Coast, USA

Posted 18 May 2006 - 05:59 PM

Your function would have an input in the class:
function GetUserInfo($user) {

And you would call it like this:
$cn->GetUserInfo($user);

Alternately, you could also pass this as a value to the constructor and make it a global variable in the class if you plan to use it in other areas of the class.

Info: PHP Manual


#7 famous58

famous58
  • Members
  • PipPip
  • Member
  • 21 posts

Posted 18 May 2006 - 06:12 PM

Thanks for all of your help!
I'm trying, really I am.

#8 famous58

famous58
  • Members
  • PipPip
  • Member
  • 21 posts

Posted 18 May 2006 - 06:34 PM

[!--quoteo(post=375016:date=May 18 2006, 09:59 AM:name=ober)--][div class=\'quotetop\']QUOTE(ober @ May 18 2006, 09:59 AM) View Post[/div][div class=\'quotemain\'][!--quotec--]
Your function would have an input in the class:
function GetUserInfo($user) {

And you would call it like this:
$cn->GetUserInfo($user);

Alternately, you could also pass this as a value to the constructor and make it a global variable in the class if you plan to use it in other areas of the class.
[/quote]

OK. Here is what I changed it to:
<?php

class MySQLConnect{
    var $connection;
    
    function MySQLConnect(){
        $dbhost = "localhost";
        $dbuser = "database_user";
        $dbpass = "password";
        $dbname = "database_printing";
        
        $this->connection = mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error());
        mysql_select_db($dbname, $this->connection) or die(mysql_error());         
        }
    
    function GetUserInfo($user) {
    $query = "SELECT * users WHERE username=$user";
    $result = mysql_query($query, $this->connection);
    $row = mysql_fetch_array($result);
    
    echo "User: " . $row[username] . "<br>";
    echo "Email: " . $row[email] . "<br>";
    echo "User Level: " . $row[userlevel] . "<br>";
        }
    
    }
?>

and
<?
$user= 'admin';
include('mysqldb.php');
$output = new MySQLConnect();


?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body>
<? $output->GetUserInfo($user); ?>
</body>
</html>

But I am receiving "Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/prellisp/public_html/new/mysqldb.php on line 19"

Line 19 is the "$row = mysql_fetch_array($result);". I've triple checked my db variables and everything is correct.
I'm trying, really I am.

#9 ober

ober
  • Staff Alumni
  • Advanced Member
  • 5,337 posts
  • LocationEast Coast, USA

Posted 18 May 2006 - 06:39 PM

That means you have an SQL error, and I'm going to guess it's the fact that you don't have single quotes around $user in your query.

Info: PHP Manual


#10 famous58

famous58
  • Members
  • PipPip
  • Member
  • 21 posts

Posted 18 May 2006 - 06:44 PM

[!--quoteo(post=375032:date=May 18 2006, 10:39 AM:name=ober)--][div class=\'quotetop\']QUOTE(ober @ May 18 2006, 10:39 AM) View Post[/div][div class=\'quotemain\'][!--quotec--]
That means you have an SQL error, and I'm going to guess it's the fact that you don't have single quotes around $user in your query.
[/quote]

Tried that, changed it to "SELECT * users WHERE `username`='$user'" with no avail.
I'm trying, really I am.

#11 ober

ober
  • Staff Alumni
  • Advanced Member
  • 5,337 posts
  • LocationEast Coast, USA

Posted 18 May 2006 - 07:06 PM

Well, to be honest, I'm not sure it's going to work how you're setting up the connection. I've never successfully pass a connection around like that. That might be where your problem is.

Info: PHP Manual


#12 famous58

famous58
  • Members
  • PipPip
  • Member
  • 21 posts

Posted 18 May 2006 - 08:14 PM

[!--quoteo(post=375035:date=May 18 2006, 11:06 AM:name=ober)--][div class=\'quotetop\']QUOTE(ober @ May 18 2006, 11:06 AM) View Post[/div][div class=\'quotemain\'][!--quotec--]
Well, to be honest, I'm not sure it's going to work how you're setting up the connection. I've never successfully pass a connection around like that. That might be where your problem is.
[/quote]


Thanks for the honesty. I was kinda taking that code from another script someone else wrote anyway (http://evolt.org/node/60384) and have not been able to figure it out either. I guess I'll go back to my orginal way of connecting, but at least I understand classes a little better now.

Thanks again.
I'm trying, really I am.

#13 trq

trq
  • Staff Alumni
  • Advanced Member
  • 31,041 posts

Posted 19 May 2006 - 02:05 AM

That connection shopuld work fine, obviously your query isn't returning a result for whatever reason. You should always check your queries actually work before trying to use them.
function GetUserInfo($user) {
    $query = "SELECT * users WHERE username=$user";
    if ($result = mysql_query($query, $this->connection)) {
        $row = mysql_fetch_array($result);
    } else {
        die(mysql_error($this->connection));
    }
    
    echo "User: " . $row[username] . "<br>";
    echo "Email: " . $row[email] . "<br>";
    echo "User Level: " . $row[userlevel] . "<br>";
}
A bit abrupt, but it will work as an example.

Also, (and this is just my opinion) you should try and avoid html within your classes. The whole idea of classes is to make them as reusable as possible.

A better method might be....
class MySQLConnect{
    
    var $connection;
    var $msg;
    
    function MySQLConnect(){
        $dbhost = "localhost";
        $dbuser = "database_user";
        $dbpass = "password";
        $dbname = "database_printing";
        
        $this->connection = mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error());
        mysql_select_db($dbname, $this->connection) or die(mysql_error());        
    }
    
    function GetUserInfo($user) {
        $query = "SELECT * users WHERE username=$user";
        if ($result = mysql_query($query, $this->connection)) {
            return mysql_fetch_array($result);
        } else {
            $this->msg = mysql_error($this->error());
            return FALSE;
        }
    }

    function error() {
        return $this->msg;
    }
}
Then, to use it...
<?php
$user= 'admin';
include('mysqldb.php');
$output = new MySQLConnect();


?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body>
<?php
if ($row = $output->GetUserInfo($user)) {
    echo "User: {$row['username']}<br>";
    echo "Email: {$row['email']}<br>";
    echo "User Level: {$row['userlevel']}<br>";
} else {
    echo $output->error();
}
?>
</body>
</html>


#14 famous58

famous58
  • Members
  • PipPip
  • Member
  • 21 posts

Posted 19 May 2006 - 03:21 PM

[!--quoteo(post=375107:date=May 18 2006, 06:05 PM:name=thorpe)--][div class=\'quotetop\']QUOTE(thorpe @ May 18 2006, 06:05 PM) View Post[/div][div class=\'quotemain\'][!--quotec--]
That connection shopuld work fine, obviously your query isn't returning a result for whatever reason. You should always check your queries actually work before trying to use them.

[/quote]

I'll try that out. It seems though, everytime I try a MySQL connection inside a function, it doesn't work. If I add the connection information (along with the variable declarations) then it works. If I move them outside the function, it does not. Why is that. I see all these scripts that are written the way yours is, but it won't work for me. Is that a server setting? PHP.ini setting?

Same goes for declaring the variables. If I declare the variables in say a db.php and include that in the top of the page, if I put the connection inside a function it fails, like so:

this does not work:
<?
include ('db.php');

function Connect(){

  mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error());
  mysql_select_db($dbname, $this->connection) or die(mysql_error());
  
  }

function GetInfo(){

  $result = mysql_query( "SELECT username FROM users WHERE id='1'" );
  $row = mysql_fetch_array($result);
  }

  GetInfo();

?>


this does:
<?

function GetInfo(){

  $dbhost = "localhost";
  $dbuser = "database_user";
  $dbpass = "password";
  $dbname = "database_printing";

  mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error());
  mysql_select_db($dbname) or die(mysql_error());

  $result = mysql_query( "SELECT username FROM users WHERE id='1'" );
  $row = mysql_fetch_array($result);
  }

  GetInfo();

?>

My whole purpose of all of this is to create a function that will connect and return data without having to recreate the connection in every function in the file or on other pages where the functions are called.

T.I.A.
I'm trying, really I am.

#15 .josh

.josh
  • Staff Alumni
  • .josh
  • 14,871 posts

Posted 19 May 2006 - 03:34 PM

you need to look into global vs. local variables. if you want the function to be able to access those connection variables, you need to put like :

<?
include ('db.php');

function Connect(){
  global $dbhost;
  global $dbuser;
  global $dbpass;

  mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error());
  mysql_select_db($dbname, $this->connection) or die(mysql_error());
  
  }



Did I help you? Feeling generous? Buy me lunch! 
Please, take the time and do some research and find out how much it would have cost you to get your help from a decent paid-for source. A "roll-of-the-dice" freelancer will charge you $5-$15/hr. A decent entry level freelancer will charge you around $15-30/hr. A professional will charge you anywhere from $50-$100/hr. An agency will charge anywhere from $100-$250/hr. Think about all this when soliciting for help here. Think about how much money you are making from the work you are asking for help on. No, we do not expect you to pay for the help given here, but donating a few bucks is a fraction of the cost of what you would have paid, shows your appreciation, helps motivate people to keep offering help without the pricetag, and helps make this a higher quality free-help community :)

#16 famous58

famous58
  • Members
  • PipPip
  • Member
  • 21 posts

Posted 19 May 2006 - 03:41 PM

w00t. It was worth getting out of bed today!
I'm trying, really I am.

#17 Barand

Barand
  • Moderators
  • Sen . ( ile || sei )
  • 18,025 posts

Posted 19 May 2006 - 07:26 PM

If you're still having a problem with that query, try putting the FROM keyword in there

$query = "SELECT * [!--coloro:#FF6666--][span style=\"color:#FF6666\"][!--/coloro--]FROM [!--colorc--][/span][!--/colorc--]users WHERE username=admin";
If you are still using mysql_ functions, STOP! Use mysqli_ or PDO. The longer you leave it the more you will have to rewrite.

Donations gratefully received






moon.png

|baaGrid| easy data tables - and more
|baaChart| easy line, column and pie charts

#18 .josh

.josh
  • Staff Alumni
  • .josh
  • 14,871 posts

Posted 19 May 2006 - 08:11 PM

i thought the FROM keyword was not necessary (although useful for your own personal clarification)?
Did I help you? Feeling generous? Buy me lunch! 
Please, take the time and do some research and find out how much it would have cost you to get your help from a decent paid-for source. A "roll-of-the-dice" freelancer will charge you $5-$15/hr. A decent entry level freelancer will charge you around $15-30/hr. A professional will charge you anywhere from $50-$100/hr. An agency will charge anywhere from $100-$250/hr. Think about all this when soliciting for help here. Think about how much money you are making from the work you are asking for help on. No, we do not expect you to pay for the help given here, but donating a few bucks is a fraction of the cost of what you would have paid, shows your appreciation, helps motivate people to keep offering help without the pricetag, and helps make this a higher quality free-help community :)

#19 famous58

famous58
  • Members
  • PipPip
  • Member
  • 21 posts

Posted 19 May 2006 - 08:18 PM

[!--quoteo(post=375316:date=May 19 2006, 11:26 AM:name=Barand)--][div class=\'quotetop\']QUOTE(Barand @ May 19 2006, 11:26 AM) View Post[/div][div class=\'quotemain\'][!--quotec--]
If you're still having a problem with that query, try putting the FROM keyword in there

$query = "SELECT * [!--coloro:#FF6666--][span style=\"color:#FF6666\"][!--/coloro--]FROM [!--colorc--][/span][!--/colorc--]users WHERE username=admin";
[/quote]

That was just a typo on my part, it is in there. I do have something working now.
I'm trying, really I am.

#20 Barand

Barand
  • Moderators
  • Sen . ( ile || sei )
  • 18,025 posts

Posted 19 May 2006 - 08:32 PM

[!--quoteo(post=375328:date=May 19 2006, 09:11 PM:name=Crayon Violent)--][div class=\'quotetop\']QUOTE(Crayon Violent @ May 19 2006, 09:11 PM) View Post[/div][div class=\'quotemain\'][!--quotec--]
i thought the FROM keyword was not necessary (although useful for your own personal clarification)?
[/quote]

I get a syntax error if I omit it. I've not seen any documentation saying it's optional.
If you are still using mysql_ functions, STOP! Use mysqli_ or PDO. The longer you leave it the more you will have to rewrite.

Donations gratefully received






moon.png

|baaGrid| easy data tables - and more
|baaChart| easy line, column and pie charts




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users