Objects Orientation in PHP – Creating classes and inserting data on MYSQL database

Hey guys.. i had a really hard time finding a good and easy material on the internet about objects orientation in php, showing not only how to create an object and give values to it, but also how to insert and rescue data on MYSQL database. That’s why i’ve decided to create this tutorial to make your lives easieršŸ˜€

The idea is to create a form where it can be included products and a form to list this products by category.

Let’s create two files. The Product.class.php, that will be our class, where we will write our functions and all, and the file object.php that will be where we put the form and call the class to execute these functions.

But first let’s create our database. To do that, we need to create a query (sql code language).

You can access your website’s control panel and enter directly into phpmyadmin, but i prefer to use MySQL GUI Tools that is a package with a list of MySQL’s own tools. This package has the Mysql Query Browser which is where we can connect to the database and execute our query.

Note: If you are in any host that doesn’t let you create a table by the code, you’ll have to enter in your control panel and create it. Most of times, it goes like this: login_table

Let’s see the code now (execute the code block to block to avoid errors.

Database:

create database oo;
use oo;

Now let’s create the table categories:

CREATE TABLE categories (
‘cat_id’ int (10) unsigned NOT NULL auto_increment,
‘cat_name’ varchar (45) NOT NULL,
PRIMARY KEY (‘cat_id’)
) ENGINE = InnoDB AUTO_INCREMENT = 11 DEFAULT CHARSET = utf8;

On the code above, we are creating the table categories, the fields cat_id and cat_name. We are also saying that cat_id is the primary key and it has auto-increment.

Now we will insert data into it:

INSERT INTO categories (cat_name) VALUES
(‘Telephone’),
(‘books’),
(‘Cds, Dvds and Games’),
(‘Sport and Fun’),
(‘Info’);

Product Table:

CREATE TABLE produtos (
‘id’ int(10) unsigned NOT NULL auto_increment,
‘name’ varchar(60) NOT NULL,
‘value’ double NOT NULL,
‘quantity’ int(10) unsigned NOT NULL,
‘category’ varchar(45) NOT NULL,
PRIMARY KEYĀ  (‘id’)
) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=utf8;

The same thing as the category. Only now it is products and it has more fields.

Now I’ll post the code in php and explain with comments the necessary lines.

Product.class.php

 

<?
class Product {
/ / public and private Variables declaration
public $ connection;
public $ database;
public $ db;
public $ var;
public $ val;
public $ id;
private $ name;
private $ value;
private $ amount;
public $ cat_id;
public $ cat_name;
/ / Constructor method here we set what we want it to do to create the object
function __construct () {
/ / Create our connection to the database and select the base
$connection = mysql_pconnect(“localhost”, “username”, “password”) or die (mysql_error ());
$db = mysql_select_db(“oo”);
}
/ * The method __set is responsible for receiving the property name and value to be assigned and may assign or not* /
function __set($ var, $ val) {
$this->$var = $val;

}
setProduct function () {
/ Perform the insert into the database passing the values of the object created
$insertProdutos = mysql_query(“insert into products values (null, ‘$ this-> name’, $ this-> value ‘, $ this-> quantity’, $ this-> category’)”);
}
getProduct function () {
/ * Performs the select on the database and selects and save information in the variable $ getProdutos,
note that the foreign key was used (we use when we need to do some relationship with the tables) in this category table product.
* /
$getProducts = mysql_query (“select * from products, categories WHERE category = ‘$this->cat_id’ and category = cat_id);
/ / This while is used to get the select’s data and as long as they exist, they will be assigned to their variable and soon after showing them on screen
while ($l = mysql_fetch_array ($getProducts)) {
$this->name = $l[‘name’];
$this->value = $l[‘value’];
print ‘<br> Name:’. $this->name. “<br>”;
print ‘Value: R $’. $ this-> value. “<br>”;
}
}
/ * Function that I created to do a select in the table categories and return all the registered categories within a combo * / box (select)
getSelect function () {
$getSelect = mysql_query(“select * from categories”);
print “<label for=’category’> Category: <br>”;
print “<select name=’category’>”;
while ($l= mysql_fetch_array ($getSelect)) {
$this->cat_id = $l[“cat_id”];
$this->cat_name = $l[‘cat_name”];
/ * See the value of the option is the cat_id and the cat_name is just what appears to the user. And this cat_id that will be saved in the table categories in category field, so we can make our association * /
print “<option value='{$this->cat_id}’>{$ this->cat_nome) </option>”;
}
print “</select>”;
print “</label>”;
}
}
?>

object.php

Name = $_POST[‘name’], $product1->value = $_POST [‘value’]; $product1->quantity = $_POST[‘Quantity’] / / naming the function that makes the insert $product1-> setProduct();}>
<?
include_once (‘Product.class.php’);
/ / Get the variable GET that pass on action from form
$action = $_GET[‘action’];
/ / Check which form was submitted
switch ($action) (
/ / If it is setProduto
case “setProduct”: {
/ / Creating and Instantiating the object
$product1 = new Product;
/ / Assigning values to the object
$product1->name = $_POST[‘name’];
$product1->value = $_POST[‘value’];
$product1->quantity = $_POST[‘Quantity’];
$product1->category = $_POST[‘Category’];
/ / Calling the function that makes the insert
$product1->setProduct();
}
break;
/ / If setProduto
case “getProduct”: {
$getProduct = new Product;
$getProduct->cat_id = $_POST[‘Category’];
$getProduct->getProduct();
}
break;
}

?>
<html>
<body>
<p> Add Data </ p>
<Form action = “<? $SELF_PHP;?>?action=setProduct” method=”post”>
<label for=”Name”>
Name:
<br />
<input type=”text” name=”Name”/> </ label>
<br />
<label for=”Value”> Value:
<br />
<input type=”text” name=”Value” /> </ label>
<br />
<label for=”Quantity”> Quantity:
<br />
<input type=”text” name=”Quantity” /> </ label>
<br />

<? $getSelect = new Product;
$getSelect->getSelect();?>
<br />
<br />
<input type=”submit” value=”Submit” />
</form>
Redeem <p> Data </ p>
<form method=’post’ action=”<? $ SELF_PHP;?>?action=getProduct”>
<?$getSelect->getSelect();?>
<input type=”submit” value=”Listing products” />
</form>
</body>
</html>