Jump to content

Archived

This topic is now archived and is closed to further replies.

famous58

Introduction To PHP Classes OOP

Recommended Posts

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
[code]
<?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);
        }
    
    }
?>
[/code]

mysqldb_echo.php
[code]
<?

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>
[/code]

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.

[b]Mod Edit(shoz): connection details removed[/b]

Share this post


Link to post
Share on other sites
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:
[code]$cn = new MySQLConnect();
$cn->GetUserInfo();[/code]

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.

Share this post


Link to post
Share on other sites
[!--quoteo(post=374988:date=May 18 2006, 09:19 AM:name=ober)--][div class=\'quotetop\']QUOTE(ober @ May 18 2006, 09:19 AM) [snapback]374988[/snapback][/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:
[code]$cn = new MySQLConnect();
$cn->GetUserInfo();[/code]

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:

[code]
$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>";
[/code]

or

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

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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
[!--quoteo(post=375002:date=May 18 2006, 09:38 AM:name=ober)--][div class=\'quotetop\']QUOTE(ober @ May 18 2006, 09:38 AM) [snapback]375002[/snapback][/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.:

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

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?

Share this post


Link to post
Share on other sites
Your function would have an input in the class:
[code]function GetUserInfo($user) { [/code]

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

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.

Share this post


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

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

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:
[code]
<?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>";
        }
    
    }
?>
[/code]

and
[code]
<?
$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>[/code]

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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
[!--quoteo(post=375032:date=May 18 2006, 10:39 AM:name=ober)--][div class=\'quotetop\']QUOTE(ober @ May 18 2006, 10:39 AM) [snapback]375032[/snapback][/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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
[!--quoteo(post=375035:date=May 18 2006, 11:06 AM:name=ober)--][div class=\'quotetop\']QUOTE(ober @ May 18 2006, 11:06 AM) [snapback]375035[/snapback][/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.

Share this post


Link to post
Share on other sites
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.
[code]
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>";
}
[/code]
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....
[code]
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;
    }
}
[/code]
Then, to use it...
[code]
<?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>
[/code]

Share this post


Link to post
Share on other sites
[!--quoteo(post=375107:date=May 18 2006, 06:05 PM:name=thorpe)--][div class=\'quotetop\']QUOTE(thorpe @ May 18 2006, 06:05 PM) [snapback]375107[/snapback][/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:
[code]
<?
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();

?>

[/code]

this does:
[code]
<?

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();

?>
[/code]

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.

Share this post


Link to post
Share on other sites
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 :

[code]
<?
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());
  
  }
[/code]


Share this post


Link to post
Share on other sites
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";

Share this post


Link to post
Share on other sites
i thought the FROM keyword was not necessary (although useful for your own personal clarification)?

Share this post


Link to post
Share on other sites
[!--quoteo(post=375316:date=May 19 2006, 11:26 AM:name=Barand)--][div class=\'quotetop\']QUOTE(Barand @ May 19 2006, 11:26 AM) [snapback]375316[/snapback][/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.

Share this post


Link to post
Share on other sites
[!--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) [snapback]375328[/snapback][/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.

Share this post


Link to post
Share on other sites
oh wait i just looked in my book and yeh you're right (you're ALWAYS right). i was thinking about the INTO keyword in an INSERT query.

Share this post


Link to post
Share on other sites
you know, i've read all about classes and OOP all night...and I still don't see a purpose in using them. it seems like more work to me. anyone else feel that way?

Share this post


Link to post
Share on other sites
if used the right way they can be very useful.

im currently learning them and there aight!

Share this post


Link to post
Share on other sites
[!--quoteo--][div class=\'quotetop\']QUOTE[/div][div class=\'quotemain\'][!--quotec--]you know, i've read all about classes and OOP all night...and I still don't see a purpose in using them.[/quote]
It takes a while to [i] get it[/i], but once you do....

Most problems can be overcome with design patterns, classes and objects. Of course there not ideal for every solution.

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.