PHP class using Data class example Tutorial _php tutorial

Source: Internet
Author: User
In this section, we will kill two birds a stone. Not only will we learn how to put object-oriented PHP and MySQL, but we will learn how to group objects. In this case, you will build a first-class usersgroup which will contain a series of user objects. Each user object will be established for continuous use from the MySQL query. To try this practical example, you first need to build a user table in the MySQL database. I'm using the MySQL database named ' Kirupa_oop '. Use the following query to create a table and insert sample data.

/* Create Users Table */
CREATE TABLE ' users ' (
' user_id ' INT not NULL auto_increment,
' user_name ' TEXT is not NULL,
PRIMARY KEY (' user_id ')
);

/* Insert sample data into Users table */
INSERT into ' users '
(' user_id ', ' user_name ')
VALUES
(', ' Kirupa '),
(', ' bwh2 ');

This very simple form has only two columns: ' user_id ' and ' username '. You may wish to add your own name to this table for spice things up.

As promised, we will create a Usersgroup class. The workgroup will contain a series of user objects, each of which creates tables using data from our MySQL. The database on all my tables is named ' Kirupa_oop '. If your database does not have a name of ' Kirupa_oop ', you must change the database name in the settings class shown. Here is the action of our Usersgroup class:

$group = new Usersgroup;

/* Loop through our group, echo user names */
foreach ($group->getusers () as $user) {
echo $user->getname (). '
';
}

/* User class, same as before */
Class User {
Private $name;

function __construct ($attribs) {
$this->name = $attribs [' name '];
}

/* Name Methods */
function SetName ($val) {
$this->name = $val;
Return
}

function GetName () {
return $this->name;
}
}

/* Contains A group of User objects */
Class Usersgroup {
Private $name; Name of Group
Private $group = Array (); Group of User Objects

function __construct () {
/* Connect to DB using Settings */
$link = mysql_connect (
Settings:: $DATABASE [' Host '],
Settings:: $DATABASE [' username '],
Settings:: $DATABASE [' Password ']
);
mysql_select_db (Settings:: $DATABASE [' DATABASE '], $link);

/* Get table names from Settings class */
$tbl _users = Settings:: $TABLES [' tbl_users '];

/* Query */
$sql = "Select user_id as ID,
User_name as Name
From $tbl _users ";
$result = mysql_query ($sql) or Die (Mysql_error ());

/* Adds user to group with each row of data */
while ($row = Mysql_fetch_array ($result)) {
$this->adduser ($row);
}
}

/*
Add a user to Group
Does simple Check to see if we pass a array (like $attribs)
Or if we pass an object (like a User object)
*/
function AddUser ($user) {
if (Is_object ($user)) {
Array_push ($this->group, $user);
}
if (Is_array ($user)) {
$noob = new User ($user);
Array_push ($this->group, $noob);
}
Return
}

/* Returns the group (which is an array) */
function Getusers () {
return $this->group;
}
}

/* Holds our Site Settings */
Class Settings {
Static $DATABASE = Array (
Change these as needed ' database ' = ' Kirupa

The first thing to note is that we hold our database connection and table name set first class in our country, in static variables. If we need to change our database name, table name, database username, etc., we will only be able to do and we set the first class (which is best in a separate, including archive). Our user level is nothing new-it not only owns the name of the property, but still gets a series of data through _ _construct.

Let's take a look at the code of the Usersgroup class. If you have connected to MySQL database with PHP before, the connection should be something new. The only difference is that we use static variables for our connection settings. We do this on our name, because the double quotes within the table, our set of first-class static variables cannot be parsed. That is, only using the set:: $ table [' tbl_users '] directly in our double quotes SQL query will result in an error.

Our SQL query produces a series of rows that we specify as the result. Using the while loop, we pass our $ result array. The result of each element of the dollar is a series of values (such as number and name). Again, this should look familiar to people who use PHP to access the MySQL database. Now the object-oriented part: We then query our AddUser method from our MySQL by each row (column). First, the AddUser method checks if a series of data (such as $ line) or an entire user object is passed. In this case, we are going through a series of data. Using the array's data, AddUser creates a user object ($ noob), and then adds a group array of user objects (groups).

Note to the column name: When our user goal is to create a series of data, the construct is to look for the name of the so-called array element. To meet this requirement, we use the SQL alias to see the USD database. If we do not alias username the name of the dollar in consecutive variables will not hold the names of the so-called array elements, but the user name. Therefore, it does not correctly fill in the name of the variable in our user object. I prefer to have my custom SQL, not my PHP class method, because I'm more likely to reuse PHP class methods than SQL queries. For example, if I create a dog class, I would also like to getname methods and constructs. Instead of modifying a few PHP methods to support users rather than dogs, I would rather modify a SQL query. Alternatively, you can rename your user name bar, just the name. This will maximize reuse, but may hurt your ability to understand more complex SQL queries and database designs.

You might consider this category to be overly complex. After all, you might code all of this on a regular PHP page within 15 lines. So, where's the advantage? Well, see how we use our objects:

/* Instantiate Group */
$group = new Usersgroup;

/* Loop through our group, echo user names */
foreach ($group->getusers as $user) {
echo $user->getname (). '
';
}

http://www.bkjia.com/PHPjc/632006.html www.bkjia.com true http://www.bkjia.com/PHPjc/632006.html techarticle in this section, we will kill two birds a stone. Not only will we learn how to put object-oriented PHP and MySQL, but we will learn how to group objects. In this case, you will build a ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.