Jump to content


Photo

PHP Classes


  • Please log in to reply
3 replies to this topic

#1 seran128

seran128
  • Members
  • PipPipPip
  • Advanced Member
  • 38 posts

Posted 24 October 2006 - 05:26 PM

OK what I want to do is create a class that I can include on my other pages, call function from that class and return those resluts to the calling page. Any references to online materials on php classes would be great!

My code should be something like;


class_db.php

  class db(){

//Top level db connection

var $db_name="db_name";
var $db_host="localhost";
var $db_user="db_user";
var $db_password="db_password";


$connection=mysql_connect($db_host,$db_user,$db_password) or die("I Couldn't connect");
$db=mysql_select_db($db_name,$connection) or die("I Couldn't select your database");

function getlist($inTable){

$sql="select * from $inTable order by ID";
$result=mysql_query($sql,$connection) or die(mysql_error());

//I need to return my $result here but don't know how

}

function updatelist($inTable,$description,$id){

            $sql="update $inTable set description='$description' where regionId='$id'";
$result=mysql_query($sql,$connection) or die(mysql_error());


//I need to return my $result here but don't know how

}

function deletelist($inTable,$id){

            $sql="delete from $inTable where regionId='$id'";
$result=mysql_query($sql,$connection) or die(mysql_error());


//I need to return my $result here but don't know how

}


//also need to close any dbconnection but don't know how
//end the class
}


page.php

include("class_db.php");
.......
<?

getlist(my_table)
$i = 0;

//Need to return the output from the function so the following line can use it.

while($row=mysql_fetch_array($result)) {
$i++;
echo "<tr class=\"d".($i & 1)."\">";
?>

....other HTML code Is Here........

<? } ?>




#2 trq

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

Posted 24 October 2006 - 06:00 PM

Do you have a question?

#3 seran128

seran128
  • Members
  • PipPipPip
  • Advanced Member
  • 38 posts

Posted 24 October 2006 - 09:01 PM

My question is how do I get this to work using classes?

I would like to learn how to use classes in PHP but I have no clue on how to get data back from a function in a class.



#4 doni49

doni49
  • Members
  • PipPipPip
  • Advanced Member
  • 515 posts
  • LocationCentral MO

Posted 24 October 2006 - 11:11 PM

Access the variables and functions within the class using "->".

Example:
//myClass.inc
class myClass{
  var $testVar;
  function testFunc(){
    return $this->testVar;
  }
}

//test.php

include("myClass.inc");
$mc = new myClass;
$mc->testVar = "Hello there!";

echo $mc->testFunc();  //this will output "Hello there" to the screen

Some further reading:
http://us3.php.net/class
http://codewalkers.c...rials/54/1.html
Don




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users