Posts

display-facebook-feed-on-website

How To Display Facebook Page Posts On Website Using PHP?

Let's code!

Hey guys! We have a new Facebook script for you!

This one is closely related to our previous FB scripts: Displaying Facebook page photos and events on your website.

For those who are not familiar with it, our Facebook scripts can synchronize data, like photo albums and events, from your Facebook page to your website.

Now it's time to share with you how to do it with your Facebook page posts! Today we will display Facebook page posts on your PHP website.

Read more

php-shopping-cart-tutorial-using-cookies-1
Home PHP

PHP and MySQL Shopping Cart Tutorial – Using COOKIES To Store Cart Data

php-shopping-cart-tutorial-using-cookies-1
Previously, we have learned how to code a shopping cart using PHP SESSIONS. Today, we will learn a second way to do it. We will have a PHP shopping cart tutorial using COOKIES!

Sounds delicious, isn't it? But the cookie that we will use is not the cookie we eat. Let me explain.

In this tutorial, we'll use the HTTP cookie, also known as the web cookie or browser cookie.

It is usually a small piece of data stored in the user's browser while the user is using the site.

It is designed to be a reliable way for websites to remember useful information, such as shopping cart items, or to record any user activity on a website.

Read more

Home PHP

PHP OOP CRUD Tutorial – Step By Step Guide!


Previously, we learned how to create or insert, read, update, and delete database records with our PHP and MySQL CRUD tutorial for beginners. This time, we will learn object-oriented programming with PHP & MySQL.

This post will include the following contents:

1.0 Overview
2.0 Program output

3.0 Database table structure
3.1 Create a database
3.2 Create products table
3.3 Insert products sample data
3.4 Create categories table
3.5 Insert categories sample data
3.6 Output

4.0 Create the layout files
4.1 Create header layout file
4.2 Create footer layout file
4.3 Create custom CSS file
4.4 Output

5.0 Creating record in PHP the OOP way
5.1 Create create_product.php file
5.2 Create "Read Products" button
5.3 Get a database connection
5.4 Create the database class
5.5 Create an HTML form
5.6 Show categories drop down
5.7 Create "categories" object
5.8 Add readName() method
5.9 Code when the form was submitted
5.10 Create "products" object
5.11 Output

6.0 Reading and paging record in PHP the OOP way
6.1 Create index.php file
6.2 Add "Create Product" button
6.3 Configure pagination variables
6.4 Retrieve records from the database
6.5 Add readAll() method
6.6 Display data from the database
6.7 Add action buttons
6.8 Create paging.php file
6.9 Add countAll() method
6.10 Include paging.php file
6.11 Output

7.0 Updating record in PHP the OOP way
7.1 Create update_product.php file
7.2 Create "Read Products" button
7.3 Read one record
7.4 Add readOne() method
7.5 Put form values
7.6 Show categories dropdown
7.7 Code when form was submitted
7.8 Add update() method
7.9 Output

8.0 Read One Record in PHP the OOP way
8.1 Create read_one.php file
8.2 Read one record
8.3 Display record on HTML table
8.4 Output

9.0 Deleting record in PHP the OOP way
9.1 Put this JavaScript code in layout_footer.php
9.2 Create delete_product.php
9.3 Add delete() method
9.4 Output

10.0 Search records in PHP the OOP way
10.1 Change index.php code
10.2 Create read_template.php file
10.3 Create core.php file
10.4 Change paging.php code
10.5 Include core.php and read_template.php
10.6 Create search.php file
10.7 Add search() and countAll_BySearch() methods
10.8 Output

11.0 File upload in PHP the OOP way
11.1 Change HTML form
11.2 Set value of "image" field
11.3 Change create() method
11.4 Call uploadPhoto() method
11.5 Add uploadPhoto() method
11.6 Validate submitted file
11.7 Return error messages
11.8 Show uploaded image file
11.9 Output

12.0 How To Run The Source Code?
13.0 Download LEVEL 1 Source Code
14.0 Download LEVEL 2 Source Code
15.0 Download LEVEL 3 Source Code
16.0 Download ALL LEVELS

17.0 What's Next?
18.0 Related Tutorials
19.0 Notes

1.0 Overview

Our tutorial for today is about creating a simple database application. We can achieve it with the help of this PHP OOP CRUD tutorial. You can use this knowledge in your current or future projects.

We use Bootstrap so that our application will have a decent UI. If you're not yet familiar what Bootstrap is, and you want to learn how to use it in few steps, I highly recommend following our Bootstrap tutorial first.

There are so many PHP object-oriented programming tutorials on the web today, they have different examples and implementations. Some might be completely correct, some maybe not.

I'm writing this tutorial with a clear goal: to give the best PHP OOP CRUD tutorial for beginners. I welcome your comments and suggestions to help me achieve this.

We want to learn the correct PHP OOP implementation. There are PHP frameworks such as CakePHP, CodeIgniter, and Laravel that correctly do it.

Those things are one step higher. For now, we will learn object oriented programming with PHP & MySQL. Working with a PHP framework should be easy after following this tutorial.

2.0 Program Output - PHP OOP CRUD Tutorial

We usually have three LEVELS of source code output. But WHY? Because I believe in "Learning Progression" to ensure efficient learning. Learn more

Below are some screenshots of our script's output. You can click an image to view the larger version of it. Use the left and right arrow to navigate through the screenshots.

Please note that the following images are just output previews. New features might be added already the time you are reading this.

2.1 LEVEL 1 Source Code Output

2.2 LEVEL 2 Source Code Output

2.3 LEVEL 3 Source Code Output

The LEVEL 2 and LEVEL 3 source code outputs proves that you can add and customize more features. It's easier and faster if you will learn by following our tutorial below.

Downloading our source codes is your huge advantage as well. For now, let's proceed to the step by step tutorial of our LEVEL 1 source code. Enjoy!

3.0 Database Table Structure

The files products.sql and categories.sql are also included in the code download, located at the README folder.

3.1 Create a database

  • Open your PhpMyAdmin (http://localhost/phpmyadmin)
  • Create a new database.
  • Put php_oop_crud_level_1 as database name.
  • Click "Create" button.

3.2 Create products table

In this section, we will create the "products" table (using PhpMyAdmin) on the database we just created.

Here's how to run an SQL statement using PhpMyAdmin.

  • Click php_oop_crud_level_1 database.
  • Click "SQL" tab.
  • Copy the SQL statement below and paste it in the text area.
  • Click the "Go" button.
-- Table structure for table `products`
CREATE TABLE IF NOT EXISTS `products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(32) NOT NULL,
  `description` text NOT NULL,
  `price` int(11) NOT NULL,
  `category_id` int(11) NOT NULL,
  `created` datetime NOT NULL,
  `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=38 ;

3.3 Insert products sample data

We have to put some database records.

Run the following SQL statement using your PhpMyAdmin.

-- Dumping data for table `products`
INSERT INTO `products` (`id`, `name`, `description`, `price`, `category_id`, `created`, `modified`) VALUES
(1, 'LG P880 4X HD', 'My first awesome phone!', 336, 3, '2014-06-01 01:12:26', '2014-05-31 17:12:26'),
(2, 'Google Nexus 4', 'The most awesome phone of 2013!', 299, 2, '2014-06-01 01:12:26', '2014-05-31 17:12:26'),
(3, 'Samsung Galaxy S4', 'How about no?', 600, 3, '2014-06-01 01:12:26', '2014-05-31 17:12:26'),
(6, 'Bench Shirt', 'The best shirt!', 29, 1, '2014-06-01 01:12:26', '2014-05-31 02:12:21'),
(7, 'Lenovo Laptop', 'My business partner.', 399, 2, '2014-06-01 01:13:45', '2014-05-31 02:13:39'),
(8, 'Samsung Galaxy Tab 10.1', 'Good tablet.', 259, 2, '2014-06-01 01:14:13', '2014-05-31 02:14:08'),
(9, 'Spalding Watch', 'My sports watch.', 199, 1, '2014-06-01 01:18:36', '2014-05-31 02:18:31'),
(10, 'Sony Smart Watch', 'The coolest smart watch!', 300, 2, '2014-06-06 17:10:01', '2014-06-05 18:09:51'),
(11, 'Huawei Y300', 'For testing purposes.', 100, 2, '2014-06-06 17:11:04', '2014-06-05 18:10:54'),
(12, 'Abercrombie Lake Arnold Shirt', 'Perfect as gift!', 60, 1, '2014-06-06 17:12:21', '2014-06-05 18:12:11'),
(13, 'Abercrombie Allen Brook Shirt', 'Cool red shirt!', 70, 1, '2014-06-06 17:12:59', '2014-06-05 18:12:49'),
(25, 'Abercrombie Allen Anew Shirt', 'Awesome new shirt!', 999, 1, '2014-11-22 18:42:13', '2014-11-21 19:42:13'),
(26, 'Another product', 'Awesome product!', 555, 2, '2014-11-22 19:07:34', '2014-11-21 20:07:34'),
(27, 'Bag', 'Awesome bag for you!', 999, 1, '2014-12-04 21:11:36', '2014-12-03 22:11:36'),
(28, 'Wallet', 'You can absolutely use this one!', 799, 1, '2014-12-04 21:12:03', '2014-12-03 22:12:03'),
(30, 'Wal-mart Shirt', '', 555, 2, '2014-12-13 00:52:29', '2014-12-12 01:52:29'),
(31, 'Amanda Waller Shirt', 'New awesome shirt!', 333, 1, '2014-12-13 00:52:54', '2014-12-12 01:52:54'),
(32, 'Washing Machine Model PTRR', 'Some new product.', 999, 1, '2015-01-08 22:44:15', '2015-01-07 23:44:15');

3.4 Create categories table

Categories table are used to store product categories.

Run the following SQL statement using your PhpMyAdmin.

-- Table structure for table `categories`
CREATE TABLE IF NOT EXISTS `categories` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(256) NOT NULL,
  `created` datetime NOT NULL,
  `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;

3.5 Insert categories sample data

We are going to have "Fashion", "Electronics" and "Motors" as categories in our project. I got those three category ideas from eBay, haha!

Run the following SQL statement using your PhpMyAdmin.

-- Dumping data for table `categories`
INSERT INTO `categories` (`id`, `name`, `created`, `modified`) VALUES
(1, 'Fashion', '2014-06-01 00:35:07', '2014-05-30 17:34:33'),
(2, 'Electronics', '2014-06-01 00:35:07', '2014-05-30 17:34:33'),
(3, 'Motors', '2014-06-01 00:35:07', '2014-05-30 17:34:54');

3.6 Output

In this section, we were able to set up our database using PhpMyAdmin. It should look like the image below.

We don't have a PHP program output yet. Let's continue on the next section to achieve more output.

4.0 Create the Layout Files

To reduce some code mess, we will create the layout files with the codes and assets it needs.

4.1 Create header layout file

This layout_header.php file will be included at the beginning of the PHP files that will need it. This way, we won't have to write the same header codes every time.

We use the Bootstrap framework to make our project look good. If you're not yet familiar with you, please learn our Bootstrap tutorial here first.

Bootstrap CSS asset will be included inside the head tags.

  • Create php-oop-crud-level-1 folder and open it.
  • Create layout_header.php file.
  • Place the following code.
<!DOCTYPE html>
<html lang="en">
<head>
 
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
 
    <title><?php echo $page_title; ?></title>
 
    <!-- Latest compiled and minified Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
  
    <!-- our custom CSS -->
    <link rel="stylesheet" href="libs/css/custom.css" />
  
</head>
<body>
 
    <!-- container -->
    <div class="container">
 
        <?php
        // show page header
        echo "<div class='page-header'>
                <h1>{$page_title}</h1>
            </div>";
        ?>

4.2 Create footer layout file

This layout_footer.php will be included at the end of each PHP files that needs it. This way, we won't have to write the same footer codes every time.

The assets used in this file are:

Let's go on and create the footer layout file.

  • Open php-oop-crud-level-1 folder.
  • Create layout_footer.php file.
  • Place the following code.
    </div>
    <!-- /container -->
 
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
 
<!-- Latest compiled and minified Bootstrap JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  
<!-- bootbox library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.4.0/bootbox.min.js"></script>
 
</body>
</html>

4.3 Create custom CSS file

This file is used to change any style we want on our web page. It is also used to override the default style given by Bootstrap.

  • Open php-oop-crud-level-1 folder.
  • Create libs folder.
  • Create css folder.
  • Create custom.css file.
  • Place the following code.
.left-margin{
    margin:0 .5em 0 0;
}
 
.right-button-margin{
    margin: 0 0 1em 0;
    overflow: hidden;
}
 
/* some changes in bootstrap modal */
.modal-body {
    padding: 20px 20px 0px 20px !important;
    text-align: center !important;
}
 
.modal-footer{
    text-align: center !important;
}

4.4 Output

The layout files we created in this section is meant to be used inside another PHP file. If we try to run the layout files alone, we won't get any meaningful output.

If you run layout_header.php, it will look like this on the browser.

The custom.css file will look like this.

The layout_footer.php is blank. Let's continue on the next section to see a more meaningful output.

5.0 Creating record in PHP the OOP Way

5.1 Create a file: create_product.php

Go back to php-oop-crud-level-1 folder, create a file with a name create_product.php and put the following code inside it.

<?php
// set page headers
$page_title = "Create Product";
include_once "layout_header.php";
 
// contents will be here
 
// footer
include_once "layout_footer.php";
?>

5.2 Create a "Read Products" Button

The following code will render a button. Replace the comments // contents will be here of the previous section with the following.

echo "<div class='right-button-margin'>
        <a href='index.php' class='btn btn-default pull-right'>Read Products</a>
    </div>";
 
?>
<!-- 'create product' html form will be here -->
<?php

5.3 Get a Database Connection

We can use it for retrieving categories or saving new product record later. Put the following code before // set page headers comment of create_product.php file.

// include database and object files
include_once 'config/database.php';
include_once 'objects/product.php';
include_once 'objects/category.php';
 
// get database connection
$database = new Database();
$db = $database->getConnection();
 
// pass connection to objects
$product = new Product($db);
$category = new Category($db);

5.4 Create the Database Configuration Class

Getting a database connection will not work without this class. This class file will be included in most PHP files of our PHP OOP CRUD Tutorial.

Create a config folder and inside that folder, create a database.php file. Open that file and put the following code.

<?php
class Database{
  
    // specify your own database credentials
    private $host = "localhost";
    private $db_name = "php_oop_crud_level_1";
    private $username = "root";
    private $password = "";
    public $conn;
  
    // get the database connection
    public function getConnection(){
  
        $this->conn = null;
  
        try{
            $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
        }catch(PDOException $exception){
            echo "Connection error: " . $exception->getMessage();
        }
  
        return $this->conn;
    }
}
?>

5.5 Create a Form in create_product.php

The following code will render an HTML form. Open create_product.php file.

Replace <!-- 'create product' html form will be here --> comment with the following code.

<!-- PHP post code will be here -->
 
<!-- HTML form for creating a product -->
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
 
    <table class='table table-hover table-responsive table-bordered'>
 
        <tr>
            <td>Name</td>
            <td><input type='text' name='name' class='form-control' /></td>
        </tr>
 
        <tr>
            <td>Price</td>
            <td><input type='text' name='price' class='form-control' /></td>
        </tr>
 
        <tr>
            <td>Description</td>
            <td><textarea name='description' class='form-control'></textarea></td>
        </tr>
 
        <tr>
            <td>Category</td>
            <td>
            <!-- categories from database will be here -->
            </td>
        </tr>
 
        <tr>
            <td></td>
            <td>
                <button type="submit" class="btn btn-primary">Create</button>
            </td>
        </tr>
 
    </table>
</form>

5.6 Loop Through the Categories Records to show as Drop-down

The following code will retrieve categories and put it in a "select" drop-down.

Replace <!-- categories from database will be here --> comment of the previous section with the following code.

<?php
// read the product categories from the database
$stmt = $category->read();
 
// put them in a select drop-down
echo "<select class='form-control' name='category_id'>";
    echo "<option>Select category...</option>";
 
    while ($row_category = $stmt->fetch(PDO::FETCH_ASSOC)){
        extract($row_category);
        echo "<option value='{$id}'>{$name}</option>";
    }
 
echo "</select>";
?>

5.7 Create the Object Class for Categories

Of course, the previous section won't work without the category object class. Create objects folder. Create category.php file. Place the following code.

<?php
class Category{
 
    // database connection and table name
    private $conn;
    private $table_name = "categories";
 
    // object properties
    public $id;
    public $name;
 
    public function __construct($db){
        $this->conn = $db;
    }
 
    // used by select drop-down list
    function read(){
        //select all data
        $query = "SELECT
                    id, name
                FROM
                    " . $this->table_name . "
                ORDER BY
                    name";  
 
        $stmt = $this->conn->prepare( $query );
        $stmt->execute();
 
        return $stmt;
    }
 
}
?>

5.8 Prepare readName() method

It will get the category name instead of showing just an ID. Add the following code inside our category.php, you will see this method used in the next few sections.

// used to read category name by its ID
function readName(){
     
    $query = "SELECT name FROM " . $this->table_name . " WHERE id = ? limit 0,1";
 
    $stmt = $this->conn->prepare( $query );
    $stmt->bindParam(1, $this->id);
    $stmt->execute();
 
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
     
    $this->name = $row['name'];
}

5.9 Code when the Form was Submitted

The user will enter the values in the HTML form and when the create (submit) button was clicked, values will be sent via POST request, the code below will save it in the database.

Open create_product.php file. Replace <!-- PHP post code will be here --> comment with the following code.

<?php 
// if the form was submitted - PHP OOP CRUD Tutorial
if($_POST){
 
    // set product property values
    $product->name = $_POST['name'];
    $product->price = $_POST['price'];
    $product->description = $_POST['description'];
    $product->category_id = $_POST['category_id'];
 
    // create the product
    if($product->create()){
        echo "<div class='alert alert-success'>Product was created.</div>";
    }
 
    // if unable to create the product, tell the user
    else{
        echo "<div class='alert alert-danger'>Unable to create product.</div>";
    }
}
?>

5.10 Create the Object Class for Products

The previous section will not work without the product object. Open objects folder. Create product.php file. Open that file and put the following code.

<?php
class Product{
 
    // database connection and table name
    private $conn;
    private $table_name = "products";
 
    // object properties
    public $id;
    public $name;
    public $price;
    public $description;
    public $category_id;
    public $timestamp;
 
    public function __construct($db){
        $this->conn = $db;
    }
 
    // create product
    function create(){
 
        //write query
        $query = "INSERT INTO
                    " . $this->table_name . "
                SET
                    name=:name, price=:price, description=:description, category_id=:category_id, created=:created";
 
        $stmt = $this->conn->prepare($query);
 
        // posted values
        $this->name=htmlspecialchars(strip_tags($this->name));
        $this->price=htmlspecialchars(strip_tags($this->price));
        $this->description=htmlspecialchars(strip_tags($this->description));
        $this->category_id=htmlspecialchars(strip_tags($this->category_id));
 
        // to get time-stamp for 'created' field
        $this->timestamp = date('Y-m-d H:i:s');
 
        // bind values 
        $stmt->bindParam(":name", $this->name);
        $stmt->bindParam(":price", $this->price);
        $stmt->bindParam(":description", $this->description);
        $stmt->bindParam(":category_id", $this->category_id);
        $stmt->bindParam(":created", $this->timestamp);
 
        if($stmt->execute()){
            return true;
        }else{
            return false;
        }
 
    }
}
?>

5.11 Output

Form to create product.

Categories drop down in the form.

When you fill out the form and clicked the "Create" button.

Changes in the database.

6.0 Reading and Paging Record in PHP the OOP Way

In this part of our PHP OOP CRUD tutorial, we will list the records from the database.

6.1 Create File: index.php

Create a new file and name it index.php. This file will show the main page of our web app. Put the following code inside it.

<?php
// set page header
$page_title = "Read Products";
include_once "layout_header.php";
 
// contents will be here
 
// set page footer
include_once "layout_footer.php";
?>

6.2 Add a "Create Product" button

The following code will render a button. When this button was clicked, it will show us a page where we can create a record. Replace the // contents will be here comments in the previous section with the following code.

echo "<div class='right-button-margin'>
    <a href='create_product.php' class='btn btn-default pull-right'>Create Product</a>
</div>";

6.3 Configure Pagination Variables

Pagination is very important if you have thousands of data from the database. Put the following code before the set page header comment of index.php file.

// page given in URL parameter, default page is one
$page = isset($_GET['page']) ? $_GET['page'] : 1;
 
// set number of records per page
$records_per_page = 5;
 
// calculate for the query LIMIT clause
$from_record_num = ($records_per_page * $page) - $records_per_page;
 
// retrieve records here

6.4 Retrieve Records from the Database

Now we will retrieve data from the database. Replace // retrieve records here comment of index.php with the following code.

// include database and object files
include_once 'config/database.php';
include_once 'objects/product.php';
include_once 'objects/category.php';
 
// instantiate database and objects
$database = new Database();
$db = $database->getConnection();
 
$product = new Product($db);
$category = new Category($db);
 
// query products
$stmt = $product->readAll($from_record_num, $records_per_page);
$num = $stmt->rowCount();

6.5 Add readAll() Method in product.php

Retrieving records in the previous section won't work without this method. Put the following code inside our "product.php" file which is inside the "objects" folder.

function readAll($from_record_num, $records_per_page){
 
    $query = "SELECT
                id, name, description, price, category_id
            FROM
                " . $this->table_name . "
            ORDER BY
                name ASC
            LIMIT
                {$from_record_num}, {$records_per_page}";
 
    $stmt = $this->conn->prepare( $query );
    $stmt->execute();
 
    return $stmt;
}

6.6 Display data from the database

This time, we will show the list of records to the user. An HTML table will hold our data. Put the following code after the section 6.2 code.

// display the products if there are any
if($num>0){
 
    echo "<table class='table table-hover table-responsive table-bordered'>";
        echo "<tr>";
            echo "<th>Product</th>";
            echo "<th>Price</th>";
            echo "<th>Description</th>";
            echo "<th>Category</th>";
            echo "<th>Actions</th>";
        echo "</tr>";
 
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
 
            extract($row);
 
            echo "<tr>";
                echo "<td>{$name}</td>";
                echo "<td>{$price}</td>";
                echo "<td>{$description}</td>";
                echo "<td>";
                    $category->id = $category_id;
                    $category->readName();
                    echo $category->name;
                echo "</td>";
 
                echo "<td>";
                    // read one, edit and delete button will be here
                echo "</td>";
 
            echo "</tr>";
 
        }
 
    echo "</table>";
 
    // paging buttons will be here
}
 
// tell the user there are no products
else{
    echo "<div class='alert alert-info'>No products found.</div>";
}

6.7 Put the Read, Edit and Delete Action Buttons

The following code will render three buttons: Read, Edit and Delete button.

Inside the "while" loop of the previous section, there is a comment "read one, edit and delete button will be here", replace that with the following code.

// read, edit and delete buttons
echo "<a href='read_one.php?id={$id}' class='btn btn-primary left-margin'>
    <span class='glyphicon glyphicon-list'></span> Read
</a>
 
<a href='update_product.php?id={$id}' class='btn btn-info left-margin'>
    <span class='glyphicon glyphicon-edit'></span> Edit
</a>
 
<a delete-id='{$id}' class='btn btn-danger delete-object'>
    <span class='glyphicon glyphicon-remove'></span> Delete
</a>";

6.8 Create paging.php for Paging Buttons

The following code will show our pagination buttons. Create a new file and name it "paging.php". Open that file and put the following code.

<?php
echo "<ul class='pagination'>";
 
// button for first page
if($page>1){
    echo "<li><a href='{$page_url}' title='Go to the first page.'>";
        echo "First";
    echo "</a></li>";
}
 
// calculate total pages
$total_pages = ceil($total_rows / $records_per_page);
 
// range of links to show
$range = 2;
 
// display links to 'range of pages' around 'current page'
$initial_num = $page - $range;
$condition_limit_num = ($page + $range)  + 1;
 
for ($x=$initial_num; $x<$condition_limit_num; $x++) {
 
    // be sure '$x is greater than 0' AND 'less than or equal to the $total_pages'
    if (($x > 0) && ($x <= $total_pages)) {
 
        // current page
        if ($x == $page) {
            echo "<li class='active'><a href=\"#\">$x <span class=\"sr-only\">(current)</span></a></li>";
        } 
 
        // not current page
        else {
            echo "<li><a href='{$page_url}page=$x'>$x</a></li>";
        }
    }
}
 
// button for last page
if($page<$total_pages){
    echo "<li><a href='" .$page_url. "page={$total_pages}' title='Last page is {$total_pages}.'>";
        echo "Last";
    echo "</a></li>";
}
 
echo "</ul>";
?>

6.9 Add the countAll() method in objects/product.php

The following code will be used to count the total number of records in the database. This will be used for pagination.

Open your product.php file which is inside the "objects" folder. Add the following method in the class.

// used for paging products
public function countAll(){
 
    $query = "SELECT id FROM " . $this->table_name . "";
 
    $stmt = $this->conn->prepare( $query );
    $stmt->execute();
 
    $num = $stmt->rowCount();
 
    return $num;
}

6.10 Include paging.php in index.php

The following code will show our pagination buttons under our records list. Put the following code after the closing "table" tag of section 6.6 above.

// the page where this paging is used
$page_url = "index.php?";
 
// count all products in the database to calculate total pages
$total_rows = $product->countAll();
 
// paging buttons here
include_once 'paging.php';

6.11 Output

Run http://localhost/php-oop-crud-level-1/index.php on your browser, you should see something like the image below.

List of records, page 1.

List of records, page 2.

7.0 Updating Record in PHP the OOP Way

I know our PHP OOP CRUD tutorial is kinda long. Please take a break or drink some coffee first!

7.1 Create File: update_product.php

Create update_product.php file, open that file and put the following code.

<?php
// retrieve one product will be here
 
// set page header
$page_title = "Update Product";
include_once "layout_header.php";
 
// contents will be here
 
// set page footer
include_once "layout_footer.php";
?>

7.2 Create a "Read Products" Button

The following code will render a button. This button, when clicked, will let us go back to the records list. Replace the previous section's "contents will be here" comments with the following code.

echo "<div class='right-button-margin'>
          <a href='index.php' class='btn btn-default pull-right'>Read Products</a>
     </div>";
 
?>
<!-- 'update product' form will be here -->

7.3 Retrieve One Product Information Based on the Given ID.

The following code will retrieve data that will populate our HTML form. This is important because this will let the user know what exactly the record he is updating.

Open update_product.php file. Replace "// retrieve one product will be here" comment with the following code.

// get ID of the product to be edited
$id = isset($_GET['id']) ? $_GET['id'] : die('ERROR: missing ID.');
 
// include database and object files
include_once 'config/database.php';
include_once 'objects/product.php';
include_once 'objects/category.php';
 
// get database connection
$database = new Database();
$db = $database->getConnection();
 
// prepare objects
$product = new Product($db);
$category = new Category($db);
 
// set ID property of product to be edited
$product->id = $id;
 
// read the details of product to be edited
$product->readOne();

7.4 Add readOne() method in the Product Object Class.

The readOne() method used in the previous section will not work without the following code inside /objects/product.php file.

function readOne(){
 
    $query = "SELECT
                name, price, description, category_id
            FROM
                " . $this->table_name . "
            WHERE
                id = ?
            LIMIT
                0,1";
 
    $stmt = $this->conn->prepare( $query );
    $stmt->bindParam(1, $this->id);
    $stmt->execute();
 
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
 
    $this->name = $row['name'];
    $this->price = $row['price'];
    $this->description = $row['description'];
    $this->category_id = $row['category_id'];
}

7.5 Put the Values in the Form.

Now we can put the latest values to each form elements. Replace "<!-- 'update product' form will be here -->" comment of update_product.php with the following code.

<!-- post code will be here -->
 
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"] . "?id={$id}");?>" method="post">
    <table class='table table-hover table-responsive table-bordered'>
 
        <tr>
            <td>Name</td>
            <td><input type='text' name='name' value='<?php echo $product->name; ?>' class='form-control' /></td>
        </tr>
 
        <tr>
            <td>Price</td>
            <td><input type='text' name='price' value='<?php echo $product->price; ?>' class='form-control' /></td>
        </tr>
 
        <tr>
            <td>Description</td>
            <td><textarea name='description' class='form-control'><?php echo $product->description; ?></textarea></td>
        </tr>
 
        <tr>
            <td>Category</td>
            <td>
                <!-- categories select drop-down will be here -->
            </td>
        </tr>
 
        <tr>
            <td></td>
            <td>
                <button type="submit" class="btn btn-primary">Update</button>
            </td>
        </tr>
 
    </table>
</form>

7.6 Loop Through the Categories Records to show as Drop-down

The following code will list the categories in a drop-down.

Notice that we put "if($product->category_id==$category_id){..." inside the while loop. This is to pre-select the option of the current record.

Replace the previous section's comments "categories select drop-down will be here" with the following code.

<?php
$stmt = $category->read();
 
// put them in a select drop-down
echo "<select class='form-control' name='category_id'>";
 
    echo "<option>Please select...</option>";
    while ($row_category = $stmt->fetch(PDO::FETCH_ASSOC)){
        $category_id=$row_category['id'];
        $category_name = $row_category['name'];
 
        // current category of the product must be selected
        if($product->category_id==$category_id){
            echo "<option value='$category_id' selected>";
        }else{
            echo "<option value='$category_id'>";
        }
 
        echo "$category_name</option>";
    }
echo "</select>";
?>

7.7 Code When Form was Submitted

The following code will assign the "posted" values to the object properties. Once assigned, it will update the database with those values using the update() method.

Open update_product.php file. Replace <!-- post code will be here -->" comment with the following code.

<?php 
// if the form was submitted
if($_POST){
 
    // set product property values
    $product->name = $_POST['name'];
    $product->price = $_POST['price'];
    $product->description = $_POST['description'];
    $product->category_id = $_POST['category_id'];
 
    // update the product
    if($product->update()){
        echo "<div class='alert alert-success alert-dismissable'>";
            echo "Product was updated.";
        echo "</div>";
    }
 
    // if unable to update the product, tell the user
    else{
        echo "<div class='alert alert-danger alert-dismissable'>";
            echo "Unable to update product.";
        echo "</div>";
    }
}
?>

7.8 Update Code in the Product Class

The following code will make the previous section's "$product->update()" method work. Open our "product.php" which is inside the "objects" folder and add the following code.

function update(){
 
    $query = "UPDATE
                " . $this->table_name . "
            SET
                name = :name,
                price = :price,
                description = :description,
                category_id  = :category_id
            WHERE
                id = :id";
 
    $stmt = $this->conn->prepare($query);
 
    // posted values
    $this->name=htmlspecialchars(strip_tags($this->name));
    $this->price=htmlspecialchars(strip_tags($this->price));
    $this->description=htmlspecialchars(strip_tags($this->description));
    $this->category_id=htmlspecialchars(strip_tags($this->category_id));
    $this->id=htmlspecialchars(strip_tags($this->id));
 
    // bind parameters
    $stmt->bindParam(':name', $this->name);
    $stmt->bindParam(':price', $this->price);
    $stmt->bindParam(':description', $this->description);
    $stmt->bindParam(':category_id', $this->category_id);
    $stmt->bindParam(':id', $this->id);
 
    // execute the query
    if($stmt->execute()){
        return true;
    }
 
    return false;
     
}

7.9 Output

Click any "Edit" button in the index page. The update record form should look like the following.

When you submit the form, a message will be shown.

A record was changed in the database.

8.0 Read One Record in PHP the OOP Way

We previously made the code for "update record", this section for reading one record from a database will be easier to do.

8.1 Create read_one.php file

This is the page where the data of a single record will be displayed. Create a new file and name it "read_one.php", open that file and put the following code.

<?php
// set page headers
$page_title = "Read One Product";
include_once "layout_header.php";
 
// read products button
echo "<div class='right-button-margin'>";
    echo "<a href='index.php' class='btn btn-primary pull-right'>";
        echo "<span class='glyphicon glyphicon-list'></span> Read Products";
    echo "</a>";
echo "</div>";
 
// set footer
include_once "layout_footer.php";
?>

8.2 Read one record based on given record ID

The following code will read a single record from the database. Put the following code before the "set page headers" comments of the previous section.

// get ID of the product to be read
$id = isset($_GET['id']) ? $_GET['id'] : die('ERROR: missing ID.');
 
// include database and object files
include_once 'config/database.php';
include_once 'objects/product.php';
include_once 'objects/category.php';
 
// get database connection
$database = new Database();
$db = $database->getConnection();
 
// prepare objects
$product = new Product($db);
$category = new Category($db);
 
// set ID property of product to be read
$product->id = $id;
 
// read the details of product to be read
$product->readOne();

8.3 Display record on HTML table

This time, we will display the record details on an HTML table. Put the following code under the closing "div" tag of "Read Products" button.

// HTML table for displaying a product details
echo "<table class='table table-hover table-responsive table-bordered'>";
 
    echo "<tr>";
        echo "<td>Name</td>";
        echo "<td>{$product->name}</td>";
    echo "</tr>";
 
    echo "<tr>";
        echo "<td>Price</td>";
        echo "<td>${$product->price}</td>";
    echo "</tr>";
 
    echo "<tr>";
        echo "<td>Description</td>";
        echo "<td>{$product->description}</td>";
    echo "</tr>";
 
    echo "<tr>";
        echo "<td>Category</td>";
        echo "<td>";
            // display category name
            $category->id=$product->category_id;
            $category->readName();
            echo $category->name;
        echo "</td>";
    echo "</tr>";
 
echo "</table>";

8.4 Output

Click any "Read" button in the index page, you should see something like the image below.

9.0 Deleting Record in PHP the OOP Way

This is the last coding part of our PHP OOP CRUD Tutorial. Enjoy every code!

9.1 Put this JavaScript code in layout_footer.php

Put the following JavaScript code before the closing "body" tag in layout_footer.php file. We used Bootbox.js to make a Bootstrap-style confirm dialog box.

<script>
// JavaScript for deleting product
$(document).on('click', '.delete-object', function(){
 
    var id = $(this).attr('delete-id');
 
    bootbox.confirm({
        message: "<h4>Are you sure?</h4>",
        buttons: {
            confirm: {
                label: '<span class="glyphicon glyphicon-ok"></span> Yes',
                className: 'btn-danger'
            },
            cancel: {
                label: '<span class="glyphicon glyphicon-remove"></span> No',
                className: 'btn-primary'
            }
        },
        callback: function (result) {
 
            if(result==true){
                $.post('delete_product.php', {
                    object_id: id
                }, function(data){
                    location.reload();
                }).fail(function() {
                    alert('Unable to delete.');
                });
            }
        }
    });
 
    return false;
});
</script>

9.2 Create delete_product.php

Create a new file and name it "delete_product.php". This file accepts the ID posted by the JavaScript code in the previous section. A record will be deleted from the database based on posted ID.

Open delete_product.php and put the following code.

<?php
// check if value was posted
if($_POST){
 
    // include database and object file
    include_once 'config/database.php';
    include_once 'objects/product.php';
 
    // get database connection
    $database = new Database();
    $db = $database->getConnection();
 
    // prepare product object
    $product = new Product($db);
     
    // set product id to be deleted
    $product->id = $_POST['object_id'];
     
    // delete the product
    if($product->delete()){
        echo "Object was deleted.";
    }
     
    // if unable to delete the product
    else{
        echo "Unable to delete object.";
    }
}
?>

9.3 Delete Code in Product Class

The previous section will not work with the "delete()" method in the product object. Open "product.php" which is inside the "objects" folder and put the following code.

// delete the product
function delete(){
 
    $query = "DELETE FROM " . $this->table_name . " WHERE id = ?";
     
    $stmt = $this->conn->prepare($query);
    $stmt->bindParam(1, $this->id);
 
    if($result = $stmt->execute()){
        return true;
    }else{
        return false;
    }
}

9.4 Output

Click any "Delete" button in the index page. A pop up confirmation will be shown.

If the user clicks "OK" the record will be deleted and gone in the table.

A record was deleted in the database.

10.0 Search Records in PHP the OOP Way

We'll continue by adding the search feature. This will answer the question: How to search data from database in php? This is a very useful feature because you enable your users to easily search a certain data from our MySQL database.

Please note that this is a bonus section. The code in this section is not included in our LEVEL 1 source code download.

10.1 Change index.php

We have to change index.php because we are adding a “search” feature and we want our code to be short. Our index.php will now look like the following code.

<?php
// core.php holds pagination variables
include_once 'config/core.php';
 
// include database and object files
include_once 'config/database.php';
include_once 'objects/product.php';
include_once 'objects/category.php';
 
// instantiate database and product object
$database = new Database();
$db = $database->getConnection();
 
$product = new Product($db);
$category = new Category($db);
 
$page_title = "Read Products";
include_once "layout_header.php";
 
// query products
$stmt = $product->readAll($from_record_num, $records_per_page);
 
// specify the page where paging is used
$page_url = "index.php?";
 
// count total rows - used for pagination
$total_rows=$product->countAll();
 
// read_template.php controls how the product list will be rendered
include_once "read_template.php";
 
// layout_footer.php holds our javascript and closing html tags
include_once "layout_footer.php";
?>

10.2 Create read_template.php

Why do we need this template? We need it because exactly the same code can be used by index.php and search.php for displaying a list of records. Using a template means lesser code.

This template holds our search form as well.

<?php
// search form
echo "<form role='search' action='search.php'>";
    echo "<div class='input-group col-md-3 pull-left margin-right-1em'>";
        $search_value=isset($search_term) ? "value='{$search_term}'" : "";
        echo "<input type='text' class='form-control' placeholder='Type product name or description...' name='s' id='srch-term' required {$search_value} />";
        echo "<div class='input-group-btn'>";
            echo "<button class='btn btn-primary' type='submit'><i class='glyphicon glyphicon-search'></i></button>";
        echo "</div>";
    echo "</div>";
echo "</form>";
 
// create product button
echo "<div class='right-button-margin'>";
    echo "<a href='create_product.php' class='btn btn-primary pull-right'>";
        echo "<span class='glyphicon glyphicon-plus'></span> Create Product";
    echo "</a>";
echo "</div>";
 
// display the products if there are any
if($total_rows>0){
 
    echo "<table class='table table-hover table-responsive table-bordered'>";
        echo "<tr>";
            echo "<th>Product</th>";
            echo "<th>Price</th>";
            echo "<th>Description</th>";
            echo "<th>Category</th>";
            echo "<th>Actions</th>";
        echo "</tr>";
 
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
 
            extract($row);
 
            echo "<tr>";
                echo "<td>{$name}</td>";
                echo "<td>{$price}</td>";
                echo "<td>{$description}</td>";
                echo "<td>";
                    $category->id = $category_id;
                    $category->readName();
                    echo $category->name;
                echo "</td>";
 
                echo "<td>";
 
                    // read product button
                    echo "<a href='read_one.php?id={$id}' class='btn btn-primary left-margin'>";
                        echo "<span class='glyphicon glyphicon-list'></span> Read";
                    echo "</a>";
 
                    // edit product button
                    echo "<a href='update_product.php?id={$id}' class='btn btn-info left-margin'>";
                        echo "<span class='glyphicon glyphicon-edit'></span> Edit";
                    echo "</a>";
 
                    // delete product button
                    echo "<a delete-id='{$id}' class='btn btn-danger delete-object'>";
                        echo "<span class='glyphicon glyphicon-remove'></span> Delete";
                    echo "</a>";
 
                echo "</td>";
 
            echo "</tr>";
 
        }
 
    echo "</table>";
 
    // paging buttons
    include_once 'paging.php';
}
 
// tell the user there are no products
else{
    echo "<div class='alert alert-danger'>No products found.</div>";
}
?>

10.3 Create core.php in "config" folder

Create a new folder and name it "config". Inside that folder, create a new file and name it "core.php".

This file will hold our pagination variables. Using a core.php file is a good practice, it can be used to hold other configuration values that you might need in the future.

Open core.php and put the following code.

<?php
// page given in URL parameter, default page is one
$page = isset($_GET['page']) ? $_GET['page'] : 1; 
 
// set number of records per page
$records_per_page = 5;
 
// calculate for the query LIMIT clause
$from_record_num = ($records_per_page * $page) - $records_per_page;
?>

10.4 Change paging.php code

The new paging.php code will look like the following.

<?php
echo "<ul class=\"pagination\">";
 
// button for first page
if($page>1){
    echo "<li><a href='{$page_url}' title='Go to the first page.'>";
        echo "First Page";
    echo "</a></li>";
}
 
// count all products in the database to calculate total pages
$total_pages = ceil($total_rows / $records_per_page);
 
// range of links to show
$range = 2;
 
// display links to 'range of pages' around 'current page'
$initial_num = $page - $range;
$condition_limit_num = ($page + $range)  + 1;
 
for ($x=$initial_num; $x<$condition_limit_num; $x++) {
 
    // be sure '$x is greater than 0' AND 'less than or equal to the $total_pages'
    if (($x > 0) && ($x <= $total_pages)) {
 
        // current page
        if ($x == $page) {
            echo "<li class='active'><a href=\"#\">$x <span class=\"sr-only\">(current)</span></a></li>";
        }
 
        // not current page
        else {
            echo "<li><a href='{$page_url}page=$x'>$x</a></li>";
        }
    }
}
 
// button for last page
if($page<$total_pages){
    echo "<li><a href='" .$page_url . "page={$total_pages}' title='Last page is {$total_pages}.'>";
        echo "Last Page";
    echo "</a></li>";
}
 
echo "</ul>";
?>

10.5 Include core.php and read_template.php

The core.php file will be included at the beginning of index.php file. The read_template.php will be included before the layout_footer.php inclusion. The new index.php will look like the following code

<?php
// core.php holds pagination variables
include_once 'config/core.php';
 
// include database and object files
include_once 'config/database.php';
include_once 'objects/product.php';
include_once 'objects/category.php';
 
// instantiate database and product object
$database = new Database();
$db = $database->getConnection();
 
$product = new Product($db);
$category = new Category($db);
 
$page_title = "Read Products";
include_once "layout_header.php";
 
// query products
$stmt = $product->readAll($from_record_num, $records_per_page);
 
// specify the page where paging is used
$page_url = "index.php?";
 
// count total rows - used for pagination
$total_rows=$product->countAll();
 
// read_template.php controls how the product list will be rendered
include_once "read_template.php";
 
// layout_footer.php holds our javascript and closing html tags
include_once "layout_footer.php";
?>

10.6 Create search.php

This is the most important file of this section. This file will display the records based on a user's search term.

Create a new file and name it "search.php". Open that file and put the following code.

<?php
// core.php holds pagination variables
include_once 'config/core.php';
 
// include database and object files
include_once 'config/database.php';
include_once 'objects/product.php';
include_once 'objects/category.php';
 
// instantiate database and product object
$database = new Database();
$db = $database->getConnection();
 
$product = new Product($db);
$category = new Category($db);
 
// get search term
$search_term=isset($_GET['s']) ? $_GET['s'] : '';
 
$page_title = "You searched for \"{$search_term}\"";
include_once "layout_header.php";
 
// query products
$stmt = $product->search($search_term, $from_record_num, $records_per_page);
 
// specify the page where paging is used
$page_url="search.php?s={$search_term}&";
 
// count total rows - used for pagination
$total_rows=$product->countAll_BySearch($search_term);
 
// read_template.php controls how the product list will be rendered
include_once "read_template.php";
 
// layout_footer.php holds our javascript and closing html tags
include_once "layout_footer.php";
?>

10.7 Add search() and countAll_BySearch() methods

Open "product.php" file which is inside the "objects" folder. Add the following methods in the class.

// read products by search term
public function search($search_term, $from_record_num, $records_per_page){
 
    // select query
    $query = "SELECT
                c.name as category_name, p.id, p.name, p.description, p.price, p.category_id, p.created
            FROM
                " . $this->table_name . " p
                LEFT JOIN
                    categories c
                        ON p.category_id = c.id
            WHERE
                p.name LIKE ? OR p.description LIKE ?
            ORDER BY
                p.name ASC
            LIMIT
                ?, ?";
 
    // prepare query statement
    $stmt = $this->conn->prepare( $query );
 
    // bind variable values
    $search_term = "%{$search_term}%";
    $stmt->bindParam(1, $search_term);
    $stmt->bindParam(2, $search_term);
    $stmt->bindParam(3, $from_record_num, PDO::PARAM_INT);
    $stmt->bindParam(4, $records_per_page, PDO::PARAM_INT);
 
    // execute query
    $stmt->execute();
 
    // return values from database
    return $stmt;
}
 
public function countAll_BySearch($search_term){
 
    // select query
    $query = "SELECT
                COUNT(*) as total_rows
            FROM
                " . $this->table_name . " p 
            WHERE
                p.name LIKE ? OR p.description LIKE ?";
 
    // prepare query statement
    $stmt = $this->conn->prepare( $query );
 
    // bind variable values
    $search_term = "%{$search_term}%";
    $stmt->bindParam(1, $search_term);
    $stmt->bindParam(2, $search_term);
 
    $stmt->execute();
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
 
    return $row['total_rows'];
}

10.8 Output

php-mysql-oop-crud-tutorial

11.0 File Upload in PHP the OOP Way

In this section, we will add a "file upload" feature. This feature is included in the LEVEL 2 source code download.

11.1 Change HTML form

Open create_product.php and find the "form" tag. Change that line to the following code. The "enctype" enables the form to submit a file to the server.

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" enctype="multipart/form-data">

On the same HTML table, find the closing "tr" tag of the "Category" field. Add the following code. This adds an input field where the user can browse the file he wants to upload.

<tr>
    <td>Photo</td>
    <td><input type="file" name="image" /></td>
</tr>

11.2 Set value of "image" field

Open create_product.php and add the new "image" field. The value will be the file name of the submitted file. We used the built-in sha1_file() function the make the file name unique.

Open create_product.php file. Place the following code under $product->category_id = $_POST['category_id']; code.

$image=!empty($_FILES["image"]["name"])
        ? sha1_file($_FILES['image']['tmp_name']) . "-" . basename($_FILES["image"]["name"]) : "";
$product->image = $image;

11.3 Change create() method

Open "objects" folder and open the "product.php" file inside it. Find the "create()" method.

Add the "image" field by changing the query to:

// insert query
$query = "INSERT INTO " . $this->table_name . "
            SET name=:name, price=:price, description=:description,
                category_id=:category_id, image=:image, created=:created";

On the sanitize section, it will be:

$this->image=htmlspecialchars(strip_tags($this->image));

Then bind the value.

$stmt->bindParam(":image", $this->image);

Add the "image" property at the top of the class, maybe after public $category_id;

public $image;

Using the PhpMyAdmin, add an "image" field in the products table. Set the type to VARCHAR with 512 in length.

11.4 Call uploadPhoto() method

Open create_product.php and find this line.

// product was created in database
echo "<div class='alert alert-success'>Product was created.</div>";

Put the following code under the code above. This will call the uploadPhoto() method that will try to upload the file to server.

// try to upload the submitted file
// uploadPhoto() method will return an error message, if any.
echo $product->uploadPhoto();

11.5 Add uploadPhoto() method

The previous section will not work without the complete code of uploadPhoto() method.

Open "objects" folder and open the "product.php" file inside it. Add the following method inside the class.

// will upload image file to server
function uploadPhoto(){
 
    $result_message="";
 
    // now, if image is not empty, try to upload the image
    if($this->image){
 
        // sha1_file() function is used to make a unique file name
        $target_directory = "uploads/";
        $target_file = $target_directory . $this->image;
        $file_type = pathinfo($target_file, PATHINFO_EXTENSION);
 
        // error message is empty
        $file_upload_error_messages="";
 
    }
 
    return $result_message;
}

11.6 Validate submitted file

Now we will validate the submitted file by:

  • Identifying if it's a real or fake image.
  • Limit the allowed file types.
  • Prevent multiple file on the server.
  • Deny uploading files with large file size.
  • Making sure the "uploads" directory exists.

Add the following code after $file_upload_error_messages=""; of the previous section.

// make sure that file is a real image
$check = getimagesize($_FILES["image"]["tmp_name"]);
if($check!==false){
    // submitted file is an image
}else{
    $file_upload_error_messages.="<div>Submitted file is not an image.</div>";
}
 
// make sure certain file types are allowed
$allowed_file_types=array("jpg", "jpeg", "png", "gif");
if(!in_array($file_type, $allowed_file_types)){
    $file_upload_error_messages.="<div>Only JPG, JPEG, PNG, GIF files are allowed.</div>";
}
 
// make sure file does not exist
if(file_exists($target_file)){
    $file_upload_error_messages.="<div>Image already exists. Try to change file name.</div>";
}
 
// make sure submitted file is not too large, can't be larger than 1 MB
if($_FILES['image']['size'] > (1024000)){
    $file_upload_error_messages.="<div>Image must be less than 1 MB in size.</div>";
}
 
// make sure the 'uploads' folder exists
// if not, create it
if(!is_dir($target_directory)){
    mkdir($target_directory, 0777, true);
}

11.7 Return error messages

If the file is valid, we will upload the file to server. Specifically, in the "uploads" folder. If there's any error, we will return it to be shown to the user.

Place the following code after the previous section's code.

// if $file_upload_error_messages is still empty
if(empty($file_upload_error_messages)){
    // it means there are no errors, so try to upload the file
    if(move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)){
        // it means photo was uploaded
    }else{
        $result_message.="<div class='alert alert-danger'>";
            $result_message.="<div>Unable to upload photo.</div>";
            $result_message.="<div>Update the record to upload photo.</div>";
        $result_message.="</div>";
    }
}
 
// if $file_upload_error_messages is NOT empty
else{
    // it means there are some errors, so show them to user
    $result_message.="<div class='alert alert-danger'>";
        $result_message.="{$file_upload_error_messages}";
        $result_message.="<div>Update the record to upload photo.</div>";
    $result_message.="</div>";
}

11.8 Show uploaded image file

Open "objects" folder and open "product.php" file. Find readOne() method. Add the "image" field in the method. The new method should look like the following.

function readOne(){
 
    $query = "SELECT name, price, description, category_id, image
        FROM " . $this->table_name . "
        WHERE id = ?
        LIMIT 0,1";
 
    $stmt = $this->conn->prepare( $query );
    $stmt->bindParam(1, $this->id);
    $stmt->execute();
 
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
 
    $this->name = $row['name'];
    $this->price = $row['price'];
    $this->description = $row['description'];
    $this->category_id = $row['category_id'];
    $this->image = $row['image'];
}

Open read_one.php file and find the closing "tr" tag of the "Category" field in the HTML table. Add the following code. This will show the uploaded image.

echo "<tr>";
    echo "<td>Image</td>";
    echo "<td>";
        echo $product->image ? "<img src='uploads/{$product->image}' style='width:300px;' />" : "No image found.";
    echo "</td>";
echo "</tr>";

11.9 Output

Click the "Create" button, you will see something like the image below.

When you submitted the form, it will show a message prompt.

If you tried to upload an invalid image file, for example a PDF file. It will show an error message.

If you click the "Read" button of a record with an image, it will look like the following.

If the record has no image, it will say "No image found." message.

12.0 How To Run The Source Codes?

We highly recommend for you to follow and study our well-detailed, step-by-step tutorial above first. Nothing beats experience when it comes to learning.

But we believe you will learn faster if you’ll see the final source code as well. We consider it as your additional guide.

Imagine the value or skill upgrade it can bring you. The additional income you can get from your work, projects or business. The precious time you save. Isn’t that what you want?

By now, you need to download our source codes. To do it, use any download buttons in the next few sections below.

Once you downloaded the source codes, here’s how you can run it.

  1. Extract the files to your server directory.
  2. Create your database using PhpMyAdmin, database name is "php_oop_crud_level_3" *
  3. Import the SQL file called "php_oop_crud_level_3.sql" located in the "dev" folder.
  4. You run index.php file. For example: http://localhost/php-oop-crud-level-3/index.php

* Database name and SQL file is different for LEVEL 1 and 2 source codes.

13.0 Download LEVEL 1 Source Code

FEATURES LEVEL 1
Object Oriented Programming Source Code YES
PDO extension used YES
Create product YES
Read product YES
Update product YES
Delete product YES
Price display with dollar sign YES
Pagination YES
Bootstrap UI YES
SQL file in "dev" folder YES
Download Now

14.0 Download LEVEL 2 Source Code

FEATURES LEVEL 2
All features of LEVEL 1 above YES
HTML5 (font-end) validation for create product YES
HTML5 (font-end) validation for update product YES
Category selection for create and update product. YES
Buttons with Glyphicons YES
Search products by name or description YES
HTML5 (font-end) validation for search product YES
Pagination in search YES
Allow user to input page number (read and search list) YES
Export / download records to CSV YES
Price display with dollar sign, comma and decimal point YES
Multiple delete YES
File upload field when creating or updating record YES
Download Now

15.0 Download LEVEL 3 Source Code

FEATURES LEVEL 3
All features of LEVEL 1 and 2 above YES
Bootstrap navigation bar YES
Select category in navigation YES
Higlight category in navigation YES
Create category YES
Read category YES
Update category YES
Delete category YES
View products by category YES
Pagination for category YES
Search category YES
Pagination for category search YES
Server side validation for create product & category YES
Server side validation for update product & category YES
Sorting by fields YES
Pagination for sorting by fields YES
jQuery UI enabled YES
Search product by date range - record date created YES
Pagination for earch product by date range YES
jQuery UI calendar for picking date YES
Download Now

16.0 Download ALL LEVELS

This means you will download the LEVEL 1, 2 and 3 source codes in separate packages. Please select "ALL LEVELS Source Code" below and then you click the "Download Now" button.

Download Now

Do you need more reasons to get it?

MORE REASONS TO DOWNLOAD THE CODE ALL
Use new skills for your multiple projects YES
Save huge amount of time learning Bootstrap and PHP YES
Code examples are direct to the point YES
Well explained and commented source code YES
Fast and friendly email support YES
Free source code updates YES

17.0 What's Next?

I hope you learned a lot from our PHP OOP CRUD Tutorial! Learning PHP Object Oriented Programming is fun and it can dramatically improve your career.

Up next: You have two choices.

A. Learn our PHP Login Script with Session Tutorial – Step by Step Guide! - Let's put our PHP OOP CRUD knowledge to work by building a simple PHP login script.

B. Learn How to create a simple REST API in PHP - Step by Step Guide! - this is required before we go to our JavaScript programming tutorials.

18.0 Related Tutorials

19.0 Notes

#1 Found An Issue?

If you found a problem with this code, please write a comment below. Please be descriptive about your issue. Please provide the error messages, screenshots (or screencast) and your test URL. Thanks!

Before you write a comment, remember to read this guide and our code of conduct.

#2 Become a true Ninja!

We constantly improve CodeOfaNinja. We update our tutorials and source codes. Receive valuable web programming tutorials and updates to your email. Subscribe now!

Enjoy high-quality web programming tutorials.
Subscribe to CodeOfaNinja now for FREE!

#3 Thank You!

Please note that this post is in continuous development, meaning I'll update it every now and then.

If you have a friend or know someone who needs this PHP OOP CRUD Tutorial, please share this page to them! I know you will help them a lot by doing it. Thanks!

Bootstrap Tutorial for Beginners – Step by Step Guide!

Bootstrap is a CSS framework that will make your web application look good, fast, and responsive. You won't have to worry about having a decent user interface when you use it.

I love Bootstrap because it solves a problem that I have. I'm not good at designing web app user interfaces. That is why I made this Bootstrap tutorial for beginners.

As proof, you will see that we are using Bootstrap in most of our tutorials. Here are some good looking websites or web apps built with the help of Bootstrap: http://expo.getbootstrap.com

Just a little history, Bootstrap was created on Twitter. It was called Twitter Bootstrap to streamline their development. Thanks to these people, the library is still in active development.

This Bootstrap tutorial for beginners will cover the following:

1.0 Include Bootstrap via CDN
2.0 Write HTML5 boilerplate
3.0 Include Bootstrap CSS
4.0 Include Bootstrap JavaScript
5.0 Add a navigation bar
6.0 Add navigation links
7.0 Add a dropdown
8.0 Add a search form
9.0 Add a content container
10.0 Add a heading
11.0 Add a table
12.0 Add form elements to a table
13.0 Add an alert message
14.0 Bootstrap online resources
15.0 What's next?
16.0 Related tutorials
17.0 Some notes

The following sections will be your step by step guide to your first web development with Bootstrap.

1.0 Include Bootstrap via CDN

We will use a CDN or Content delivery network to enable Bootstrap on our page.

Using Bootstrap CDN means that we will not download and store the bootstrap files in our server or local machine. We will just include the Bootstrap CSS and JavaScript links on our web page.

2.0 Write HTML5 boilerplate

Create new index.html file. Open the file, place the following code and save it.

<!DOCTYPE html>
<html lang="en">
<head>
 
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
 
    <title>Bootstrap Tutorial for Beginners</title>
 
    <!-- Bootstrap CSS will be here -->
</head>
<body>
 
<!-- navigation bar will be here -->
<!-- container bar will be here -->
 
<!-- Bootstrap JavaScript will be here -->
 
</body>
</html>

Our output on this section is a blank page. We do not have any contents inside the body tags. Comments are not displayed, of course.

But if we view the source, we actually made some progress!

3.0 Include Bootstrap CSS

On index.html file, replace <!-- Bootstrap CSS will be here --> with the following code.

<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
        integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

The integrity and crossorigin attributes are needed for security purposes. The answers in this question can explain it better.

Our output is still a blank page. All we can do for now is view the source to see if it was updated.

4.0 Include Bootstrap JavaScript

Bootstrap features like the navigation bar need the Bootstrap JavaScript file.

On index.html file, replace <!-- Bootstrap JavaScript will be here --> with the following code.

<!-- javascript for bootstrap -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
    integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous">
</script>
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
    integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous">
</script>
 
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
    integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous">
</script>

Output? Still a blank page. But let's view the source.

5.0 Add a navigation bar

Bootstrap Navbar, also called navigation header, is so cool. They look good on the desktop and on any mobile device. Your users won't get lost on your website if you use them properly.

On index.html file, replace <!-- navigation bar will be here --> with the following code.

<!-- navbar -->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
    <a class="navbar-brand" href="#">Navbar</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
        aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>
 
    <!-- navigation links will be here -->
</nav>
<!-- /navbar -->

Output? Yes! This is the first time (in this tutorial) that we will see something on the page.

6.0 Add navigation links

On index.html file, replace <!-- navigation links will be here --> with the following code.

<div class="collapse navbar-collapse" id="navbarSupportedContent">
    <ul class="navbar-nav mr-auto">
        <li class="nav-item active">
            <a class="nav-link" href="index.html">Home <span class="sr-only">(current)</span></a>
        </li>
        <li class="nav-item">
            <a class="nav-link" href="https://www.codeofaninja.com/2014/05/bootstrap-tutorial-beginners-step-step.html" target="_blank">Tutorial</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" href="https://www.codeofaninja.com" target="_blank">Blog</a>
        </li>
        <!-- drop down will be here -->
    </ul>
    <!-- search form will be here -->
</div>

Our output shows navigation links on the Navbar.

7.0 Add a drop down

On index.html file, replace <!-- drop down will be here --> with the following code.

<li class="nav-item dropdown">
    <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button"
        data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        Dropdown
    </a>
    <div class="dropdown-menu" aria-labelledby="navbarDropdown">
        <a class="dropdown-item" href="#">Action</a>
        <a class="dropdown-item" href="#">Another action</a>
        <div class="dropdown-divider"></div>
        <a class="dropdown-item" href="#">Something else here</a>
    </div>
</li>

Our output shows a drop down on the Navbar. Cool!

8.0 Add a search form

On index.html file, replace <!-- search form will be here --> with the following code.

<form class="form-inline my-2 my-lg-0">
    <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
    <button class="btn btn-primary my-2 my-sm-0" type="submit">Search</button>
</form>

Output shows an input box and a search button on the upper right side corner of our page.

9.0 Add content container

A Bootstrap Container is required to make our web page responsive.

On index.html file, replace <!-- container will be here --> with the following code.

<div class="container mt-5">
    <!-- heading will be here -->
    <!-- alert will be here -->
    <!-- table will be here -->
</div>

You can replace the class container with a container-fluid if you want the container to have a full width.

Nothing has changed on our output. But if you will view the source, you can see the div tag with container class.

10.0 Add a heading

A Bootstrap Heading is important because it tells the user what page he was in.

On index.html file, replace <!-- heading will be here --> with the following code.

<div class="row">
    <div class="col-sm">
        <h1>Bootstrap Sample Page with Form</h1>
    </div>
</div>

As you may have noticed, we used a div tag with a row and then col-sm class. This class enables the Bootstrap Grid System. Grid systems are used for creating page layouts through a series of rows and columns that house your content.

Output shows our heading.

11.0 Add a table

Our Bootstrap Table will hold form elements like a text box. The Bootstrap table looks good and has hover effects as well.

On index.html file, replace <!-- table will be here --> with the following code.

<div class="row">
    <div class="col-sm">
         
        <table class='table table-hover'>
 
            <tr>
                <td>Name</td>
                <td></td>
            </tr>
 
            <tr>
                <td>Contact Number</td>
                <td></td>
            </tr>
 
            <tr>
                <td>Address</td>
                <td></td>
            </tr>
 
            <tr>
                <td>List</td>
                <td></td>
            </tr>
 
            <tr>
                <td></td>
                <td></td>
            </tr>
 
        </table>
             
    </div>
</div>

Our output shows a table with a few information.

12.0 Add form elements to a table

Our Bootstrap Form example will have a few text boxes, a text area, a select drop-down list and a submit button.

On index.html file, remove the code from opening <table> tag to closing </table> table. Replace it with the following code.

<form action='#' method='post'>
    <table class='table table-hover'>
 
        <tr>
            <td>Name</td>
            <td><input type='text' name='name' class='form-control' required></td>
        </tr>
 
        <tr>
            <td>Contact Number</td>
            <td><input type='text' name='contact_number' class='form-control' required></td>
        </tr>
 
        <tr>
            <td>Address</td>
            <td><textarea name='address' class='form-control'></textarea></td>
        </tr>
 
        <tr>
            <td>List</td>
            <td>
                <select name='list_id' class='form-control'>
                    <option value='1'>List One</option>
                    <option value='2'>List Two</option>
                    <option value='3'>List Three</option>
                </select>
            </td>
        </tr>
 
        <tr>
            <td></td>
            <td>
                <button type="submit" class="btn btn-primary">
                    <span class="glyphicon glyphicon-plus"></span> Submit
                </button>
            </td>
        </tr>
 
    </table>
</form>

Our output shows our HTML form.

13.0 Add an alert message

Bootstrap Alerts are a nice way to get your user's attention. Here's how to add a good looking alert message.

On index.html file, replace <!-- alert will be here --> with the following code.

<div class="row">
    <div class="col-sm">
        <div class="alert alert-success">
            <strong>Good day!</strong> This is an example alert. Visit <a href="https://codeofaninja.com/" target="_blank">codeofaninja.com</a>!
        </div>
    </div>
</div>

Output below shows an alert message.

To change alert colors, you may replace alert-success with alert-info, alert-danger or alert-warning.

14.0 Bootstrap Online Resources

15.0 What's Next?

Up Next: Learn jQuery Tutorial for Beginners – Step By Step Guide!

16.0 Related Tutorials

17.0 Some Notes

#1 Found An Issue?

If you found a problem with this code, please write a comment below. Please be descriptive about your issue. Please provide the error messages, screenshots (or screencast) and your test URL. Thanks!

Before you write a comment, remember to read this guide and our code of conduct.

#2 Become a true Ninja!

We constantly improve CodeOfaNinja. We update our tutorials and source codes. Receive valuable web programming tutorials and updates to your email. Subscribe now!

Enjoy high-quality web programming tutorials.
Subscribe to CodeOfaNinja now for FREE!

#3 Thank You!

If you have a friend who need help and is getting started to learn Bootstrap, please share this article with them.

Is there anything else I can do to improve this post? Please share your thoughts on the comments section below.

Thanks for reading our bootstrap tutorial for beginners!

jQuery Tutorial for Beginners – Step By Step Guide!

jquery-step-by-step-tutorial-for-beginners

Previously, we learned how to use Bootstrap to make our web applications look good. This time, we will learn how to use jQuery.

Many of you asked me how to use jQuery. This tutorial is my answer to you. I want to give you links but I feel like it's easier to teach someone about something that is your own version of work! We hope you guys will find this step by step guide useful.

Contents of this tutorial include:
1.0 Getting Started with jQuery
2.0 Run jQuery in 5 Easy Steps
3.0 Download Source Code
4.0 jQuery Basic Concepts
5.0 Online Resources
6.0 What's Next?
7.0 Related Tutorials
8.0 Some Notes

1.0 Getting Started with jQuery

1.1 What is jQuery? Okay here’s the simplest definition I can give. jQuery is a JavaScript library. It can:

  1. Make your JavaScript code shorter, faster and cross browser.
  2. Manipulate your HTML, like showing or hiding something from the page.
  3. Handles events – it can do something when a user click a button or any other activity a user can do with a mouse.
  4. Animation – for example make a part of your page fade in, fade out or just simply make something move.
  5. AJAX – do a server request without refreshing your whole web page.

1.2 This post. I assume you already know basic HTML, CSS and JavaScript. In this post, aside from the simple definition of jQuery above, we are just going to have two parts:

  1. The super straightforward, step by step tutorial or guide in running a very basic jQuery script. (2.0)
  2. We are going to take a look more of the jQuery basic concepts, as shown in #1 (3.0)

2.0 Run jQuery in 5 Easy Steps

2.1 Follow the steps below – these steps will lead you to run a very basic jQuery script that does a slide and toggle.

Step 1: Create HTML page with its basic structure.

<!-- step 1 -->
<!DOCTYPE html>
<html>
<head>
    <title>jQuery Tutorial for Beginners</title>
</head>
<body>

</body>
</html>

Step 2: Add element to be clicked. We’re gonna have a button in this example, we added an ID name to this button called myButton. Add the following code inside the "body" tag.

<!-- step 2 -->
<button id='myButton'>Click to Slide or Toggle</button>

Step 3: Add the element to be shown or hidden. We’re gonna have a "p" tag with bunch of sample words inside. Add the following code below step 2′s code.

<!-- step 3 -->
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. Curabitur tortor. Pellentesque nibh. Aenean quam. In scelerisque sem at dolor. Maecenas mattis. Sed convallis tristique sem. Proin ut ligula vel nunc egestas porttitor. Morbi lectus risus, iaculis vel, suscipit quis, luctus non, massa. Fusce ac turpis quis ligula lacinia aliquet. Mauris ipsum. Nulla metus metus, ullamcorper vel, tincidunt sed, euismod in, nibh. Quisque volutpat condimentum velit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam nec ante. Sed lacinia, urna non tincidunt mattis, tortor neque adipiscing diam, a cursus ipsum ante quis turpis. Nulla facilisi. Ut fringilla. Suspendisse potenti. Nunc feugiat mi a tellus consequat imperdiet. Vestibulum sapien. Proin quam. Etiam ultrices. Suspendisse in justo eu magna luctus suscipit. Sed lectus. Integer euismod lacus luctus magna. Quisque cursus, metus vitae pharetra auctor, sem massa mattis sem, at interdum magna augue eget diam. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Morbi lacinia molestie dui. Praesent blandit dolor. Sed non quam. In vel mi sit amet augue congue elementum. Morbi in ipsum sit amet pede facilisis laoreet. Donec lacus nunc, viverra nec.
</p>

Step 4: Add the jQuery library. Aren’t you excited? You can also download your own copy of jQuery but in today’s example, we’ll be linking to Google’s copy of jQuery. Add the following code below step 3′s code.

<!-- step 4 -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>

Step 5: Add jQuery script. This script will show or hide the "p" tag and the words inside it. Notice that we selected the button by referencing our button’s ID myButton.

<!-- step 5 -->
<script>
$("#myButton").click(function () {
    $("p").slideToggle("slow");
});
</script>

3.0 Download Source Codes

You can download all the code used in this tutorial for only $9.99 $5.55!

Congratulations! You are now a jQuery coder! Just kidding. Not yet. But don’t lose hope!

To achieve being a real jQuery coder, like any other skill, it must be practiced and be well versed with its concepts. So continue to read below and make your jQuery wisdom a little bit better.

4.0 jQuery Basic Concepts

4.1 Run jQuery when DOM is ready. We didn’t implement this in our example above because I want to give you a quick look on how to run a jQuery script and it is a very small web page anyway.

But in reality, if you use jQuery in larger web pages, you have to run it when the DOM is ready. Here’s how:

$(document).ready(function() {
    // jQuery will run once everthing else in your web page is already loaded.
    // All your jQuery codes here.
});

4.2 How to Select an Element in jQuery? Learning jQuery selectors are very important because you’re dealing with HTML elements within your web page.

I’m gonna give you some of the most basic selectors being used:

// selects 'only one' HTML element with ID "myButton", such as our example above
// notice that we use hashes (#) for ids, like that of CSS
$("#myButton");

// selects all HTML elements with class "myClass", for instance: <div class='myClass'></div>
// notice that we used dots (.) for classes, like that of CSS
$(".myClass");

// selects all button HTML element, for example: <button>Click Me!</button>
$("button");

// selects all div element, example: <div>Me and all other div will be selected!</div>
$("div");

// selects all anchor link element, for example: <a href="https://codeofaninja.com/">Me and all other 'a' tags will be selected!</a>
$("a");

Learn more jQuery Selectors

4.3 jQuery Events. In our example above (2.0), we use a click event, in jQuery it was represented by the click() method. Here are some more jQuery events that you might find useful:

$("button").click(function(){
    // do something when user click the button
});

$("form").submit(function(){
    // do something when user submits a form
});

$("#myDiv").hover(function(){
    // do something when user hover an HTML element
});

$("#myTextbox").keyup(function(){
    // do something when user types on a textbox with ID myTextbox
});

Learn more jQuery Events

4.4 Animation Effects with jQuery. On our example above (2.0), the animation effect we used is the slideToggle(). Here are some other animations that you can do with jQuery:

// slide or toggle animation with a <p> tag
// you can change 'slow' to 'fast' or any number in milliseconds
$("p").slideToggle("slow");

$("p").slideToggle(1000, function() {  
    // do something when slide up or down animation is done
});

// hide the matched elements with a sliding motion.
$( "#book" ).slideUp( "slow", function() {
    // animation complete
});

// display or hide the matched elements by animating their opacity.
$( "#book" ).fadeToggle( "fast", function() {
    // animation complete
});

Learn more jQuery Animation Effect

Remember that the examples above are just some of the basics. Continue to practice, search and learn more in the process. And as always, thanks for reading!

5.0 Online Resources

6.0 What's Next?

Learn jQuery UI Tutorial for Beginners - Learn how to use date picker and other user interface interactions, effects, widgets, and themes built on top of the jQuery.

7.0 Related Tutorials

8.0 Some Notes

#1 Found An Issue?

If you found a problem with this code, please write a comment below. Please be descriptive about your issue. Please provide the error messages, screenshots (or screencast) and your test URL. Thanks!

Before you write a comment, remember to read this guide and our code of conduct.

#2 Become a true Ninja!

We constantly improve CodeOfaNinja. We update our tutorials and source codes. Receive valuable web programming tutorials and updates to your email. Subscribe now!

Enjoy high-quality web programming tutorials.
Subscribe to CodeOfaNinja now for FREE!

#3 Thank You!

Thank you for learning with our jQuery Tutorial for Beginners! Please share this tutorial to one of your friends if you have time.

jQuery UI Tutorial for Beginners – Your Step by Step Guide!

jquery-ui-tutorial-for-beginners

Previously, we learned how to use jQuery to add some interactivity to our web pages. This time, are you getting started with jQuery UI? You've come to the right place!

This step by step tutorial aims to give you a head start in using jQuery UI. You probably know what jQuery is so you want to take a beautiful step forward with jQuery UI, and that's awesome!

jQuery UI jQuery UI is a curated set of user interface interactions, effects, widgets, and themes built on top of the jQuery JavaScript Library.

Whether you're building highly interactive web applications or you just need to add a date picker to a form control, jQuery UI is a perfect choice.

For me, Bootstrap and jQuery UI look good together. It also allows us to choose from different themes available, you can even create your own theme! But this post only covers running a very simple jQuery UI script in your web browser.

Contents of this post include:

1.0 Run jQuery UI in 6 Easy Steps
2.0 jQuery UI Sample Codes
3.0 Download Source Codes
4.0 Online Resources
5.0 What’s Next?
6.0 Related Tutorials
7.0 Some Notes

1.0 Run jQuery UI in 6 Easy Steps

The following steps below will make an awesome date picker with jQuery UI. Let's code!

Step 1: Prepare your HTML file with just its basic structure.

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
        
    </head>
<body>

</body>
</html>

Step 2: Add a text box inside the tag. User will be able to click this and show a jQuery UI calendar picker later.

<input type="text" id="myDatepicker" placeholder="Click to pick date" />

Step 3: Add the jQuery library before the ending tag. This is because jQuery UI is built on top of jQuery library.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

Step 4: Add the jQuery UI library under the code of step 3. This is actually the first step in enabling jQuery UI in your page.

<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>

Step 5: Add jQuery UI theme via CSS external link, put it inside the tag, after the tag. This CSS will make our UI stylish.

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.min.css" />

Step 6: Enable jQuery UI date picker to our text box on Step 1. Add the following code under the code of step 5. This is how you make a simple text box to an awesome jQuery UI date picker.

<script>
$( "#myDatepicker" ).datepicker();
</script>

Quick Tip: Always use the minified version. For instance, use jquery-ui.min.css instead of just jquery-ui.css

Continue to read below, you will see the complete code of the steps above.

2.0 jQuery UI Sample Codes

You will have to click the text box saying "Click to pick a date" to see jQuery UI with different themes in action.

By the way, examples 2.1 and 2.2 uses Google's content delivery network to run jQuery UI, meaning you won't have to download the jQuery and jQuery UI library, you just have to include it.


2.1 jQuery UI with Smoothness theme hosted in Google CDN.

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>jQuery UI Tutorial for Beginners - smoothness theme - by codeofaninja.com</title>
        
        <!-- step 4 - include you jquery ui theme -->
        <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.min.css" />
        
    </head>
<body>

<!-- step 1 -->
<input type="text" id="myDatepicker" placeholder="Click to pick date" />

<!-- step 2 -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<!-- step 3 -->
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>

<script>
/* step 5 */
$( "#myDatepicker" ).datepicker();
</script>

</body>
</html>

2.2 jQuery UI with Vader theme hosted by Google too.

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>jQuery UI Tutorial for Beginners - vader theme - by codeofaninja.com</title>
        
        <!-- step 4 - include you jquery ui theme -->
        <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/vader/jquery-ui.min.css" />
        
    </head>
<body>

<!-- step 1 -->
<input type="text" id="myDatepicker" placeholder="Click to pick date" />

<!-- step 2 -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<!-- step 3 -->
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>

<script>
/* step 5 */
$( "#myDatepicker" ).datepicker();
</script>

</body>
</html>

2.3 What if I don't want a CDN? I want to host my own jQuery UI library? No problem, you can always go to the jQuery UI download builder, you just have to select your preferred theme using the dropdown at the lower part of the page.

jquery ui download builder

jQuery UI library is self hosted in the example code below.

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>jQuery UI Tutorial for Beginners - vader theme - by codeofaninja.com</title>
        
        <!-- step 4 - include you jquery ui theme -->
        <link rel="stylesheet" href="jquery-ui-1.10.3.custom/css/le-frog/jquery-ui-1.10.3.custom.min.css" />
        
    </head>
<body>

<!-- step 1 -->
<input type="text" id="myDatepicker" placeholder="Click to pick date" />

<!-- step 2 -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<!-- step 3 -->
<script src="jquery-ui-1.10.3.custom/js/jquery-ui-1.10.3.custom.min.js"></script>

<script>
/* step 5 */
$( "#myDatepicker" ).datepicker();
</script>

</body>
</html>

3.0 Download Source Code

You can download all the code used in this tutorial for only $9.99 $5.55!

4.0 Online Resources

Want to see more of jQuery UI? You can always visit:

5.0 What's Next?

Up Next: Learn PHP and MySQL CRUD Tutorial for Beginners - build a simple web application with PHP and MySQL database.

6.0 Related Tutorials

7.0 Some Notes

#1 Found An Issue?

If you found a problem with this code, please write a comment below. Please be descriptive about your issue. Please provide the error messages, screenshots (or screencast) and your test URL. Thanks!

Before you write a comment, remember to read this guide and our code of conduct.

#2 Become a true Ninja!

We constantly improve CodeOfaNinja. We update our tutorials and source codes. Receive valuable web programming tutorials and updates to your email. Subscribe now!

Enjoy high-quality web programming tutorials.
Subscribe to CodeOfaNinja now for FREE!

#3 Thank You!

Thanks for reading our jQuery UI tutorial for beginners!

shopping-cart-in-php-sessions
Home PHP

PHP and MySQL Shopping Cart Tutorial – Using SESSIONS To Store Cart Data

shopping-cart-in-php-sessions

Previously, we learned how to build a Shopping Cart with PHP & MySQL where we used a database to store cart items. Today, we will learn another version of it. We will use PHP session variables to store cart items.

Read more

Home PHP

PHP CRUD Tutorial for Beginners – Step By Step Guide!

Previously, we learned how to run your first PHP script. This time, we we learn CRUD operations with PHP and MySQL. CRUD stands for Create, Read, Update and Delete database records.

We will cover the following topics

1.0 Overview
2.0 Program output
3.0 File structure

4.0 Prepare the database
4.1 Create the database
4.2 Create the database table
4.3 Dump sample data on the table
4.4 Create database connection file
4.5 Output

5.0 Create or insert record in PHP
5.1 HTML5 boilerplate for create.php
5.2 HTML form to input new record data
5.3 Code create a new record
5.4 Output

6.0 Read records in PHP
6.1 Basic HTML code for index.php
6.2 Read records from the database
6.3 Add HTML table with heading
6.4 Add HTML table body
6.5 Output

7.0 Read one record in PHP
7.1 Basic HTML code for read_one.php
7.2 Read records from the database
7.3 Display record details
7.4 Output

8.0 Update record in PHP
8.1 Basic HTML code for update.php
8.2 Read a record by ID parameter
8.3 HTML form to update a record
8.4 Code to update the record
8.5 Output

9.0 Delete record in PHP
9.1 Tell the user if record was deleted
9.2 JavaScript to confirm record deletion
9.3 Delete record from the database

10.0 Pagination in PHP
10.1 Set pagination variables
10.2 Add LIMIT clause in SELECT query
10.3 Count total number of records
10.4 Include paging file
10.5 Create paging.php
10.6 Add first page button
10.7 Add clickable page numbers
10.8 Add last page button
10.9 Output

11.0 File upload in PHP
11.1 Add HTML "file" field
11.2 Add "image" field
11.3 Set variables for file upload
11.4 Make sure submitted file is a real image
11.5 Make sure certain file types are allowed
11.6 Make sure file does not exist
11.7 make sure submitted file is not too large
11.8 Make sure the 'uploads' folder exists
11.9 Try to upload the file
11.10 Output

12.0 Show uploaded image in PHP
12.1 Add image field in query
12.2 Add HTML image tag
12.3 Output

13.0 How to run the source code?
14.0 Download LEVEL 1 source code
15.0 Download LEVEL 2 source code
16.0 Download LEVEL 3 source code
17.0 Download ALL LEVELS

18.0 Online resources
19.0 What's next?
20.0 Related tutorials
21.0 Notes

1.0 Overview

This tutorial is for your if:

  • You need a high quality and updated reference for a PHP CRUD tutorial.
  • You need to learn how to do CRUD operations in PHP and MySQL.
  • You are beginner in this kind of PHP web programming.

Coding CRUD with PHP and MySQL is one of the basics. PHP web programmers must be able to code it with less effort. We can perform this task using any of the three PHP Database extensions:

  1. Using the MySQL extension.
  2. Using the MySQLi extension.
  3. Using the PDO extension.

PHP 5.5 deprecated the MySQL extension. It is not recommended to use these days.

If you are programming with PHP, you'll have to use either MySQLi (i means improved) or PDO extension.

With that in mind, we will use the PDO extension. It is the newest and actively developed way of programming these CRUD grids.

2.0 PHP CRUD tutorial program output

We usually have three LEVELS of source code output. But WHY? Because I believe in "Learning Progression" to ensure efficient learning. Learn more

Below are some screenshots of our script's output. You can click an image to view the larger version of it. Use the left and right arrow to navigate through the screenshots.

Please note that the following images are just output previews. New features might be added already the time you are reading this.

2.1 LEVEL 1 source code output

2.2 LEVEL 2 source code output

2.3 LEVEL 3 source code output

The LEVEL 2 and LEVEL 3 source code outputs proves that you can add and customize more features. It's easier and faster if you will learn by following our tutorial below.

Downloading our source codes is your huge advantage as well. For now, let's proceed to the step by step tutorial of our LEVEL 1 source code. Enjoy!

3.0 Project file structure

Our PHP CRUD tutorial will contain the following main files.

  • dev/products.sql – contains the database table structure and sample data used in this project. Once you created your database in PhpMyAdmin, you can import this file.
  • config/database.php – used for database connection and configuration.
  • create.php – used for creating a new record. It contains an HTML form where the user can enter details for a new record.
  • index.php – used for reading records from the database. It uses an HTML table to display the data retrieved from the MySQL database.
  • read_one.php – used for reading one or single record from database. It uses an HTML table to display the data retrieved from the MySQL database.
  • update.php – used for updating a record. It uses an HTML form which will be filled out with data based on the given “id” parameter.
  • delete.php – used for deleting a record. It accepts an “id” parameter and deletes the record with it. Once it execute the delete query, it will redirect the user to the index.php page.

4.0 Prepare the database

4.1 Create the database

On your PhpMyAdmin, create a database named "php_beginner_crud_level_1".

If you're not sure how to do it, please take a look at the following example. Follow only the "create database" part.

4.2 Create the database table

Next, run the following SQL code. This is to create our products database table. If you're not sure how to do this, take a look at this resource.

--
-- Table structure for table `products`
--

CREATE TABLE IF NOT EXISTS `products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(128) NOT NULL,
  `description` text NOT NULL,
  `price` double NOT NULL,
  `created` datetime NOT NULL,
  `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;

4.3 Dump sample data on the table

Again, run the following SQL code on your PhpMyAdmin. This will insert the sample data or record on our products database table.

--
-- Dumping data for table `products`
--

INSERT INTO `products` (`id`, `name`, `description`, `price`, `created`, `modified`) VALUES
(1, 'Basketball', 'A ball used in the NBA.', 49.99, '2015-08-02 12:04:03', '2015-08-06 06:59:18'),
(3, 'Gatorade', 'This is a very good drink for athletes.', 1.99, '2015-08-02 12:14:29', '2015-08-06 06:59:18'),
(4, 'Eye Glasses', 'It will make you read better.', 6, '2015-08-02 12:15:04', '2015-08-06 06:59:18'),
(5, 'Trash Can', 'It will help you maintain cleanliness.', 3.95, '2015-08-02 12:16:08', '2015-08-06 06:59:18'),
(6, 'Mouse', 'Very useful if you love your computer.', 11.35, '2015-08-02 12:17:58', '2015-08-06 06:59:18'),
(7, 'Earphone', 'You need this one if you love music.', 7, '2015-08-02 12:18:21', '2015-08-06 06:59:18'),
(8, 'Pillow', 'Sleeping well is important.', 8.99, '2015-08-02 12:18:56', '2015-08-06 06:59:18');

As you may have noticed, steps 1 and 2 are both SQL queries. Yes, they can run at the same time. But I wanted it to be on separate steps to emphasize those SQL queries' purpose.

4.4 Create database connection file

This section will answer the question: how to connect to MySQL database with PDO?

  • Create php-beginner-crud-level-1 folder and open it.
  • Create config folder and open it.
  • Create database.php file.
  • Place the following code inside it.
<?php
// used to connect to the database
$host = "localhost";
$db_name = "php_beginner_crud_level_1";
$username = "root";
$password = "";
 
try {
    $con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}
 
// show error
catch(PDOException $exception){
    echo "Connection error: " . $exception->getMessage();
}
?>

4.5 Output

We have set up the database successfully! The only output we have so far is the database, database table and sample records we setup via PhpMyAdmin.

Let's proceed to the next section below.

5.0 Create or insert record in PHP

5.1 HTML5 boilerplate for create.php

We use Bootstrap user interface for this project. If you are not familiar with Bootstrap, please learn our Bootstrap Tutorial for Beginners.

  • Go back to php-beginner-crud-level-1 folder.
  • Create a new create.php file.
  • Place the code following code inside the create.php file.
<!DOCTYPE HTML>
<html>
<head>
    <title>PDO - Create a Record - PHP CRUD Tutorial</title>
     
    <!-- Latest compiled and minified Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
         
</head>
<body>
 
    <!-- container -->
    <div class="container">
  
        <div class="page-header">
            <h1>Create Product</h1>
        </div>
     
    <!-- html form to create product will be here -->
         
    </div> <!-- end .container -->
     
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
  
<!-- Latest compiled and minified Bootstrap JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 
</body>
</html>

5.2 HTML form to input new record data

Now we are going to start answering the question: how to create a record with PDO?

The code below will create an HTML form with input fields that matches the fields in the database. Replace <!-- html form to create product will be here --> comment of the previous section with the following code.

<!-- PHP insert code will be here -->

<!-- html form here where the product information will be entered -->
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
	<table class='table table-hover table-responsive table-bordered'>
		<tr>
			<td>Name</td>
			<td><input type='text' name='name' class='form-control' /></td>
		</tr>
		<tr>
			<td>Description</td>
			<td><textarea name='description' class='form-control'></textarea></td>
		</tr>
		<tr>
			<td>Price</td>
			<td><input type='text' name='price' class='form-control' /></td>
		</tr>
		<tr>
			<td></td>
			<td>
				<input type='submit' value='Save' class='btn btn-primary' />
				<a href='index.php' class='btn btn-danger'>Back to read products</a>
			</td>
		</tr>
	</table>
</form>

5.3 Code to create a new record

We are still working in the create.php file. Once the user filled out the form and clicked the save button, the code below will save it to the MySQL database.

Replace <!-- PHP insert code will be here --> comment of the previous section with the following code.

<?php
if($_POST){

	// include database connection
	include 'config/database.php';

	try{
	
		// insert query
		$query = "INSERT INTO products SET name=:name, description=:description, price=:price, created=:created";

		// prepare query for execution
		$stmt = $con->prepare($query);

		// posted values
		$name=htmlspecialchars(strip_tags($_POST['name']));
		$description=htmlspecialchars(strip_tags($_POST['description']));
		$price=htmlspecialchars(strip_tags($_POST['price']));

		// bind the parameters
		$stmt->bindParam(':name', $name);
		$stmt->bindParam(':description', $description);
		$stmt->bindParam(':price', $price);
		
		// specify when this record was inserted to the database
		$created=date('Y-m-d H:i:s');
		$stmt->bindParam(':created', $created);
		
		// Execute the query
		if($stmt->execute()){
			echo "<div class='alert alert-success'>Record was saved.</div>";
		}else{
			echo "<div class='alert alert-danger'>Unable to save record.</div>";
		}
		
	}
	
	// show error
	catch(PDOException $exception){
		die('ERROR: ' . $exception->getMessage());
	}
}
?>

5.4 Output

Congrats! For the first time, we can now see an output on a web page. Go to this URL:

http://localhost/php-beginner-crud-level-1/create.php

You will see the output that looks like the following images.

When user fill out the form.

When user submitted the form.

New record added to database.

6.0 Read records in PHP

6.1 Basic HTML code for index.php

Create new index.php file. We prepare this to read records from the database. It answers the question: how to read records with PDO?

Place the following code inside the index.php file.

<!DOCTYPE HTML>
<html>
<head>
	<title>PDO - Read Records - PHP CRUD Tutorial</title>
	
	<!-- Latest compiled and minified Bootstrap CSS -->
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
		
	<!-- custom css -->
	<style>
	.m-r-1em{ margin-right:1em; }
	.m-b-1em{ margin-bottom:1em; }
	.m-l-1em{ margin-left:1em; }
	.mt0{ margin-top:0; }
	</style>

</head>
<body>

    <!-- container -->
    <div class="container">
 
        <div class="page-header">
            <h1>Read Products</h1>
        </div>
	
        <!-- PHP code to read records will be here -->
		
    </div> <!-- end .container -->
	
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
  
<!-- Latest compiled and minified Bootstrap JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<!-- confirm delete record will be here -->

</body>
</html>

6.2 Read records from the database

This time we will read records from the database.

Replace <!-- PHP code to read records will be here --> comment of the previous section with the following code.

<?php
// include database connection
include 'config/database.php';

// delete message prompt will be here

// select all data
$query = "SELECT id, name, description, price FROM products ORDER BY id DESC";
$stmt = $con->prepare($query);
$stmt->execute();

// this is how to get number of rows returned
$num = $stmt->rowCount();

// link to create record form
echo "<a href='create.php' class='btn btn-primary m-b-1em'>Create New Product</a>";

//check if more than 0 record found
if($num>0){

	// data from database will be here
	
}

// if no records found
else{
	echo "<div class='alert alert-danger'>No records found.</div>";
}
?>

6.3 Add HTML table with heading

This is the HTML table that will hold and display data from the database.

Replace // data from database will be here comment of the previous section with the following code.

echo "<table class='table table-hover table-responsive table-bordered'>";//start table

	//creating our table heading
	echo "<tr>";
		echo "<th>ID</th>";
		echo "<th>Name</th>";
		echo "<th>Description</th>";
		echo "<th>Price</th>";
		echo "<th>Action</th>";
	echo "</tr>";
	
	// table body will be here

// end table
echo "</table>";

6.4 Add HTML table body

This part is where we will loop through the list of records from the database. This loop will create the rows of data on our HTML table.

Replace // table body will be here comment of the previous section with the following code.

// retrieve our table contents
// fetch() is faster than fetchAll()
// http://stackoverflow.com/questions/2770630/pdofetchall-vs-pdofetch-in-a-loop
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
	// extract row
	// this will make $row['firstname'] to
	// just $firstname only
	extract($row);
	
	// creating new table row per record
	echo "<tr>";
		echo "<td>{$id}</td>";
		echo "<td>{$name}</td>";
		echo "<td>{$description}</td>";
		echo "<td>${$price}</td>";
		echo "<td>";
			// read one record 
			echo "<a href='read_one.php?id={$id}' class='btn btn-info m-r-1em'>Read</a>";
			
			// we will use this links on next part of this post
			echo "<a href='update.php?id={$id}' class='btn btn-primary m-r-1em'>Edit</a>";

			// we will use this links on next part of this post
			echo "<a href='#' onclick='delete_user({$id});'  class='btn btn-danger'>Delete</a>";
		echo "</td>";
	echo "</tr>";
}

6.5 Output

Go to this URL:

http://localhost/php-beginner-crud-level-1/index.php

You will see the records retrieved from the database. It will look like the image below.

7.0 Read one record in PHP

7.1 Basic HTML code for read_one.php

Create new read_one.php file. This is where we will read and display the details of a single database record.

Place the following code inside read_one.php file.

<!DOCTYPE HTML>
<html>
<head>
	<title>PDO - Read One Record - PHP CRUD Tutorial</title>

    <!-- Latest compiled and minified Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />

</head>
<body>


    <!-- container -->
    <div class="container">
 
        <div class="page-header">
            <h1>Read Product</h1>
        </div>
		
        <!-- PHP read one record will be here -->

        <!-- HTML read one record table will be here -->

	</div> <!-- end .container -->
	
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
  
<!-- Latest compiled and minified Bootstrap JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</body>
</html>

7.2 Read one record from the database

The following code is how we retrieve a single database record.

Replace <!-- PHP read one record will be here --> comment of the previous section with the following code.

<?php
// get passed parameter value, in this case, the record ID
// isset() is a PHP function used to verify if a value is there or not
$id=isset($_GET['id']) ? $_GET['id'] : die('ERROR: Record ID not found.');

//include database connection
include 'config/database.php';

// read current record's data
try {
	// prepare select query
	$query = "SELECT id, name, description, price FROM products WHERE id = ? LIMIT 0,1";
	$stmt = $con->prepare( $query );

	// this is the first question mark
	$stmt->bindParam(1, $id);

	// execute our query
	$stmt->execute();

	// store retrieved row to a variable
	$row = $stmt->fetch(PDO::FETCH_ASSOC);

	// values to fill up our form
	$name = $row['name'];
	$description = $row['description'];
	$price = $row['price'];
}

// show error
catch(PDOException $exception){
	die('ERROR: ' . $exception->getMessage());
}
?>

7.3 Display record details

The following HTML table will hold and display the details of a single database record.

Open read_one.php file.

Replace <!-- HTML read one record table will be here --> comment with the following code.

<!--we have our html table here where the record will be displayed-->
<table class='table table-hover table-responsive table-bordered'>
	<tr>
		<td>Name</td>
		<td><?php echo htmlspecialchars($name, ENT_QUOTES);  ?></td>
	</tr>
	<tr>
		<td>Description</td>
		<td><?php echo htmlspecialchars($description, ENT_QUOTES);  ?></td>
	</tr>
	<tr>
		<td>Price</td>
		<td><?php echo htmlspecialchars($price, ENT_QUOTES);  ?></td>
	</tr>
	<tr>
		<td></td>
		<td>
			<a href='index.php' class='btn btn-danger'>Back to read products</a>
		</td>
	</tr>
</table>

7.4 Output

To read one record from the database, try to click any Read button from our index.php file.

You can also go to this URL:

http://localhost/php-beginner-crud-level-1/read_one.php?id=9

You will see an output like the image below.

8.0 Update record in PHP

8.1 Basic HTML code for udpate.php

Create new update.php file. We are preparing to update a selected record from the database.

This will answer the question: how to update a record with PDO?

Place the following code inside the new update.php file.

<!DOCTYPE HTML>
<html>
<head>
	<title>PDO - Update a Record - PHP CRUD Tutorial</title>
	
    <!-- Latest compiled and minified Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
		
</head>
<body>

    <!-- container -->
    <div class="container">
 
        <div class="page-header">
            <h1>Update Product</h1>
        </div>
	
        <!-- PHP read record by ID will be here -->

        <!-- HTML form to update record will be here -->
		
    </div> <!-- end .container -->
	
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
  
<!-- Latest compiled and minified Bootstrap JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</body>
</html>

8.2 Read a record by ID parameter

We have to get the record ID and store it in the $id variable. We access the $_GET['id'] variable to do it.

What we are trying to do here is to get the related data based on the given record ID. This is the way to auto-fill the HTML form with existing data from the database.

Replace <!-- PHP read record by ID will be here --> comment of the previous section with the following code.

<?php
// get passed parameter value, in this case, the record ID
// isset() is a PHP function used to verify if a value is there or not
$id=isset($_GET['id']) ? $_GET['id'] : die('ERROR: Record ID not found.');

//include database connection
include 'config/database.php';

// read current record's data
try {
	// prepare select query
	$query = "SELECT id, name, description, price FROM products WHERE id = ? LIMIT 0,1";
	$stmt = $con->prepare( $query );
	
	// this is the first question mark
	$stmt->bindParam(1, $id);
	
	// execute our query
	$stmt->execute();
	
	// store retrieved row to a variable
	$row = $stmt->fetch(PDO::FETCH_ASSOC);
	
	// values to fill up our form
	$name = $row['name'];
	$description = $row['description'];
	$price = $row['price'];
}

// show error
catch(PDOException $exception){
	die('ERROR: ' . $exception->getMessage());
}
?>

8.3 HTML form to update a record

This form will show the data retrieved using the previous section's code.

We read a single record from the database, based on given ID parameter.

Open update.php file. Replace <!-- HTML form to update record will be here --> comment with the following code.

<!-- PHP post to update record will be here -->

<!--we have our html form here where new record information can be updated-->
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"] . "?id={$id}");?>" method="post">
	<table class='table table-hover table-responsive table-bordered'>
		<tr>
			<td>Name</td>
			<td><input type='text' name='name' value="<?php echo htmlspecialchars($name, ENT_QUOTES);  ?>" class='form-control' /></td>
		</tr>
		<tr>
			<td>Description</td>
			<td><textarea name='description' class='form-control'><?php echo htmlspecialchars($description, ENT_QUOTES);  ?></textarea></td>
		</tr>
		<tr>
			<td>Price</td>
			<td><input type='text' name='price' value="<?php echo htmlspecialchars($price, ENT_QUOTES);  ?>" class='form-control' /></td>
		</tr>
		<tr>
			<td></td>
			<td>
				<input type='submit' value='Save Changes' class='btn btn-primary' />
				<a href='index.php' class='btn btn-danger'>Back to read products</a>
			</td>
		</tr>
	</table>
</form>

8.4 Code to update the record

The following code will save the changes in the database.

That is if the user change some value on the form and hit the Save Changes button.

Replace <!-- PHP post to update record will be here --> comment of the previous section with the following code.

<?php

// check if form was submitted
if($_POST){
	
	try{
	
		// write update query
		// in this case, it seemed like we have so many fields to pass and 
		// it is better to label them and not use question marks
		$query = "UPDATE products 
					SET name=:name, description=:description, price=:price 
					WHERE id = :id";

		// prepare query for excecution
		$stmt = $con->prepare($query);

		// posted values
		$name=htmlspecialchars(strip_tags($_POST['name']));
		$description=htmlspecialchars(strip_tags($_POST['description']));
		$price=htmlspecialchars(strip_tags($_POST['price']));

		// bind the parameters
		$stmt->bindParam(':name', $name);
		$stmt->bindParam(':description', $description);
		$stmt->bindParam(':price', $price);
		$stmt->bindParam(':id', $id);
		
		// Execute the query
		if($stmt->execute()){
			echo "<div class='alert alert-success'>Record was updated.</div>";
		}else{
			echo "<div class='alert alert-danger'>Unable to update record. Please try again.</div>";
		}
		
	}
	
	// show errors
	catch(PDOException $exception){
		die('ERROR: ' . $exception->getMessage());
	}
}
?>

8.5 Output

To update a database record, run index.php file and click any Edit button.

Or, go to this URL:

http://localhost/php-beginner-crud-level-1/update.php?id=9

You will see the result like the images below.

Update record form.

Submitted form.

Changes in the database.

9.0 Delete record in PHP

9.1 Tell the user if record was deleted

This will tell the user if there is a deleted record after clicking the delete button and OK in the pop up.

Open index.php file. Replace // delete message prompt will be here comment with the following code.

$action = isset($_GET['action']) ? $_GET['action'] : "";

// if it was redirected from delete.php
if($action=='deleted'){
	echo "<div class='alert alert-success'>Record was deleted.</div>";
}

9.2 JavaScript to confirm record deletion

The user clicks on the Delete button in index.php.

Next, he will verify the deletion by clicking OK on the pop up.

That user activity will execute the following JavaScript code.

Open index.php file. Replace <!-- confirm delete record will be here --> comment with the following code.

<script type='text/javascript'>
// confirm record deletion
function delete_user( id ){
	
	var answer = confirm('Are you sure?');
	if (answer){
		// if user clicked ok, 
		// pass the id to delete.php and execute the delete query
		window.location = 'delete.php?id=' + id;
	} 
}
</script>

9.3 Delete record from the database

The code below will delete a record from the database using the given ID parameter.

This answers the question: how to delete a record with PDO?

Create new delete.php file, place the following code and save it.

<?php
// include database connection
include 'config/database.php';

try {
	
	// get record ID
	// isset() is a PHP function used to verify if a value is there or not
	$id=isset($_GET['id']) ? $_GET['id'] : die('ERROR: Record ID not found.');

	// delete query
	$query = "DELETE FROM products WHERE id = ?";
	$stmt = $con->prepare($query);
	$stmt->bindParam(1, $id);
	
	if($stmt->execute()){
		// redirect to read records page and 
		// tell the user record was deleted
		header('Location: index.php?action=deleted');
	}else{
		die('Unable to delete record.');
	}
}

// show error
catch(PDOException $exception){
	die('ERROR: ' . $exception->getMessage());
}
?>

9.4 Output

Once user clicks any Delete button, it will show a confirmation pop up.

If user clicks the "OK" button, record will be deleted from the database. It will tell the user via message prompt that the record was deleted.

Record is gone in the database as well.

10.0 Pagination in PHP

Please note that this is a bonus section and is not included in the LEVEL 1 source code download. We will have to add or remove some codes we've done above so that pagination will work.

10.1 Set pagination variables

The following variables are used to calculate the correct numbers for the LIMIT clause of our SELECT query.

We will see how our SELECT query will change later.

Place the following code below include 'config/database.php'; line of index.php file.

// PAGINATION VARIABLES
// page is the current page, if there's nothing set, default is page 1
$page = isset($_GET['page']) ? $_GET['page'] : 1;

// set records or rows of data per page
$records_per_page = 5;

// calculate for the query LIMIT clause
$from_record_num = ($records_per_page * $page) - $records_per_page;

10.2 Add LIMIT clause in SELECT query

This will enable paginated requests to database. Still on index.php file, change the following code from:

$query = "SELECT id, name, description, price FROM products ORDER BY id DESC";
$stmt = $con->prepare($query);
$stmt->execute();

to:

// select data for current page
$query = "SELECT id, name, description, price FROM products ORDER BY id DESC
	LIMIT :from_record_num, :records_per_page";

$stmt = $con->prepare($query);
$stmt->bindParam(":from_record_num", $from_record_num, PDO::PARAM_INT);
$stmt->bindParam(":records_per_page", $records_per_page, PDO::PARAM_INT);
$stmt->execute();

10.3 Count total number of records

Counting the total number of records will help calculate the correct pagination numbers.

Below the closing table tag in index.php file, add the following code.

// PAGINATION
// count total number of rows
$query = "SELECT COUNT(*) as total_rows FROM products";
$stmt = $con->prepare($query);

// execute query
$stmt->execute();

// get total rows
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$total_rows = $row['total_rows'];

10.4 Include paging file

Add the following code after the previous section's code.

// paginate records
$page_url="index.php?";
include_once "paging.php";

Why a $page_url variable is needed? Because we made paging.php re-usable. You can use it for other objects you want to paginate.

For example you're trying to paginate your read_categories.php, you will need to do:

$page_url="read_categories.php?";

You will have to follow the code pattern of section 10.1 to 10.3 when you use paging.php file.

10.5 Create paging.php

Create new paging.php file. Place the following code and save it.

<?php
echo "<ul class='pagination pull-left margin-zero mt0'>";

// first page button will be here

// clickable page numbers will be here

// last page button will be here

echo "</ul>";
?>

10.6 Add first page button

Replace // first page button will be here comment of the previous section with the following code.

// first page button
if($page>1){

	$prev_page = $page - 1;
	echo "<li>";
		echo "<a href='{$page_url}page={$prev_page}'>";
			echo "<span style='margin:0 .5em;'>«</span>";
		echo "</a>";
	echo "</li>";
}

10.7 Add clickable page numbers

Open paging.php file.

Replace // clickable page numbers will be here comment with the following code.

// clickable page numbers

// find out total pages
$total_pages = ceil($total_rows / $records_per_page);

// range of num links to show
$range = 1;

// display links to 'range of pages' around 'current page'
$initial_num = $page - $range;
$condition_limit_num = ($page + $range)  + 1;

for ($x=$initial_num; $x<$condition_limit_num; $x++) {

	// be sure '$x is greater than 0' AND 'less than or equal to the $total_pages'
	if (($x > 0) && ($x <= $total_pages)) {

		// current page
		if ($x == $page) {
			echo "<li class='active'>";
				echo "<a href='javascript::void();'>{$x}</a>";
			echo "</li>";
		}

		// not current page
		else {
			echo "<li>";
				echo " <a href='{$page_url}page={$x}'>{$x}</a> ";
			echo "</li>";
		}
	}
}

10.8 Add last page button

Open paging.php file.

Replace // last page button will be here comment with the following code.

// last page button
if($page<$total_pages){
	$next_page = $page + 1;

	echo "<li>";
		echo "<a href='{$page_url}page={$next_page}'>";
			echo "<span style='margin:0 .5em;'>»</span>";
		echo "</a>";
	echo "</li>";
}

10.9 Output

Run index.php file on the browser:

http://localhost/php-beginner-crud-level-1/index.php

You should see the pagination buttons like the images below.

Read records page 1.

Read records page 2.

11.0 File upload in PHP

Now we are going to add a file upload feature when creating a record.

11.1 Add HTML "file" field

Open create.php file and scroll down to the form. Find the opening "form tag and enable the file upload by changing it to:

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" enctype="multipart/form-data">

Find the closing tr tag of the price field. Once found, add the following code after it.

<tr>
	<td>Photo</td>
	<td><input type="file" name="image" /></td>
</tr>

11.2 Add "image" field

Still in create.php file. Scroll up and change the insert SQL query.

It should look like the following code. The new image field will store the file name of the submitted file.

// insert query
$query = "INSERT INTO products
			SET name=:name, description=:description,
				price=:price, image=:image, created=:created";

// prepare query for execution
$stmt = $con->prepare($query);

$name=htmlspecialchars(strip_tags($_POST['name']));
$description=htmlspecialchars(strip_tags($_POST['description']));
$price=htmlspecialchars(strip_tags($_POST['price']));

// new 'image' field
$image=!empty($_FILES["image"]["name"])
		? sha1_file($_FILES['image']['tmp_name']) . "-" . basename($_FILES["image"]["name"])
		: "";
$image=htmlspecialchars(strip_tags($image));

// bind the parameters
$stmt->bindParam(':name', $name);
$stmt->bindParam(':description', $description);
$stmt->bindParam(':price', $price);
$stmt->bindParam(':image', $image);

// specify when this record was inserted to the database
$created=date('Y-m-d H:i:s');
$stmt->bindParam(':created', $created);

Using PhpMyAdmin, add an "image" field in the products table as well.

11.3 Set variables for file upload

We will start the code for the file upload feature. Find the following line in create.php file.

echo "<div class='alert alert-success'>Record was saved.</div>";

Under the code above, we will add the following code.

The if($image){ code will verify if there's an uploaded image.

If there is, inside the if statement, we will set the initial variables needed for the file upload.

// now, if image is not empty, try to upload the image
if($image){

	// sha1_file() function is used to make a unique file name
	$target_directory = "uploads/";
	$target_file = $target_directory . $image;
	$file_type = pathinfo($target_file, PATHINFO_EXTENSION);

	// error message is empty
	$file_upload_error_messages="";

}

11.4 Make sure submitted file is a real image

Now we will start validating the submitted file. The code below will identify if the submitted file is a real or fake image.

Place the following code under $file_upload_error_messages=""; of the previous section.

// make sure that file is a real image
$check = getimagesize($_FILES["image"]["tmp_name"]);
if($check!==false){
	// submitted file is an image
}else{
	$file_upload_error_messages.="<div>Submitted file is not an image.</div>";
}

11.5 Make sure certain file types are allowed

The following code will limit the allowed file types. Place it under the code of the previous section.

// make sure certain file types are allowed
$allowed_file_types=array("jpg", "jpeg", "png", "gif");
if(!in_array($file_type, $allowed_file_types)){
	$file_upload_error_messages.="<div>Only JPG, JPEG, PNG, GIF files are allowed.</div>";
}

11.6 Make sure file does not exist

There's a very small chance that the submitted file name will be the same with the one that exists in the server. This is because of the sha1_file() method we used on section 10.2 above.

But just in case there's a file with the same name, tell the user. Place the following code after the previous section's code.

// make sure file does not exist
if(file_exists($target_file)){
	$file_upload_error_messages.="<div>Image already exists. Try to change file name.</div>";
}

11.7 Make sure submitted file is not too large

Uploading a very large photo is not recommended in this case. So we will set the file size limit to less than 1 MB. Place the following code after the code of the previous section.

// make sure submitted file is not too large, can't be larger than 1 MB
if($_FILES['image']['size'] > (1024000)){
	$file_upload_error_messages.="<div>Image must be less than 1 MB in size.</div>";
}

11.8 Make sure the 'uploads' folder exists

The "uploads" folder is where we will put the submitted file. Make sure it exists by using the following code. Place it under the code of the previous section.

// make sure the 'uploads' folder exists
// if not, create it
if(!is_dir($target_directory)){
	mkdir($target_directory, 0777, true);
}

11.9 Try to upload the file

The move_uploaded_file built in PHP function will place the uploaded file on the server directory.

Place the following code under the previous section's code.

// if $file_upload_error_messages is still empty
if(empty($file_upload_error_messages)){
	// it means there are no errors, so try to upload the file
	if(move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)){
		// it means photo was uploaded
	}else{
		echo "<div class='alert alert-danger'>";
			echo "<div>Unable to upload photo.</div>";
			echo "<div>Update the record to upload photo.</div>";
		echo "</div>";
	}
}

// if $file_upload_error_messages is NOT empty
else{
	// it means there are some errors, so show them to user
	echo "<div class='alert alert-danger'>";
		echo "<div>{$file_upload_error_messages}</div>";
		echo "<div>Update the record to upload photo.</div>";
	echo "</div>";
}

11.10 Output

Form to create product with file upload field.

When form was submitted.

The "uploads" folder were created, with the uploaded file inside.

File name was saved in the database.

12.0 Show uploaded image in PHP

12.1 Add image field in query

Open read_one.php file and apply the following changes to the code.

Add image field to the $query variable. It should look like the following.

$query = "SELECT id, name, description, price, image FROM products WHERE id = ? LIMIT 0,1";

Add '$image' variable after the '$price' variable.

$image = htmlspecialchars($row['image'], ENT_QUOTES);

12.2 Add HTML image tag

Find the closing tr tag of the Price field in the HTML table and put the following code after it.

It will show the uploaded image or 'No image found.' if no image was uploaded.

<tr>
	<td>Image</td>
	<td>
	<?php echo $image ? "<img src='uploads/{$image}' style='width:300px;' />" : "No image found.";  ?>
	</td>
</tr>

12.3 Output

Click the Read One button of the record we created with a file upload.

You should see something like the images below.

Record with an image.

Record without image.

13.0 How To Run The Source Code?

We highly recommend for you to follow and study our well-detailed, step-by-step tutorial above first. Nothing beats experience when it comes to learning.

But we believe you will learn faster if you’ll see the final source code as well. We consider it as your additional guide.

Imagine the value or skill upgrade it can bring you. The additional income you can get from your work, projects or business. The precious time you save. Isn’t that what you want?

By now, you need to download our source codes. To do it, use any download buttons in the next few sections below.

Once you downloaded the source codes, here’s how you can run it.

  1. Extract the files to your server directory.
  2. Create your database using PhpMyAdmin, database name is "php_beginner_crud_3" - if you downloaded our LEVEL 3 source code.
  3. Import the SQL file called "php_beginner_crud_3.sql" located in the "dev" folder.
  4. You run index.php on the browser.

14.0 Download LEVEL 1 Source Code

FEATURES LEVEL 1
PDO extension used YES
Create product YES
Read product YES
Update product YES
Delete product YES
Price display with dollar sign YES
SQL file in "dev" folder YES
Download Now

15.0 Download LEVEL 2 Source Code

FEATURES LEVEL 2
All features of LEVEL 1 above YES
HTML5 (font-end) validation for create product YES
HTML5 (font-end) validation for update product YES
Category selection for create and update product. YES
Bootstrap UI YES
Buttons with Glyphicons YES
Pagination YES
Search products by name or description YES
HTML5 (font-end) validation for search product YES
Pagination in search YES
Allow user to input page number (read and search list) YES
Export / download records to CSV YES
Price display with dollar sign, comma and decimal point YES
Multiple delete YES
Create & update record with file upload YES
Download Now

16.0 Download LEVEL 3 Source Code

FEATURES LEVEL 3
All features of LEVEL 1 and 2 above YES
Bootstrap navigation bar YES
Select category in navigation YES
Higlight category in navigation YES
Create category YES
Read category YES
Update category YES
Delete category YES
View products by category YES
Pagination for category YES
Search category YES
Pagination for category search YES
Server side validation for create product & category YES
Server side validation for update product & category YES
Sorting by fields YES
Pagination for sorting by fields YES
jQuery UI enabled YES
Search product by date range - record date created YES
Pagination for earch product by date range YES
jQuery UI calendar for picking date YES
Download Now

17.0 Download ALL LEVELS

This means you will download the LEVEL 1, 2 and 3 source codes in separate packages. Select "ALL LEVELS Source Code" below and then you click the "Download Now" button.

Download Now

Do you need more reasons to download it?

MORE REASONS TO DOWNLOAD THE CODE ALL
Use new skills for your multiple projects YES
Save huge amount of time learning Bootstrap and PHP YES
Code examples are direct to the point YES
Well explained and commented source code YES
Fast and friendly email support YES
Free source code updates YES

If you have any more questions, please feel free to contact me now. You can do it by sending a message on our official Facebook page, or via my email [email protected]

Thanks for supporting our website and projects here at codeofaninja.com!

18.0 Online Resources

19.0 What's Next?

After learning from this PHP CRUD tutorial, we can go one step higher. We can do this by learning object-oriented programming (OOP) in PHP.

Object-oriented programming (OOP) is a programming language model organized around objects rather than "actions" and data rather than logic. This is very exciting.

To learn more, we created the next tutorial just for you! Let's go and learn:
PHP, MySQL and OOP CRUD Tutorial - Step by Step Guide!

20.0 Related Tutorials

21.0 Notes

#1 Found An Issue?

If you found a problem with this code, please write a comment below. Please be descriptive about your issue. Please provide the error messages, screenshots (or screencast) and your test URL. Thanks!

Before you write a comment, remember to read this guide and our code of conduct.

#2 Become a true Ninja!

We constantly improve CodeOfaNinja. We update our tutorials and source codes. Receive valuable web programming tutorials and updates to your email. Subscribe now!

Enjoy high-quality web programming tutorials.
Subscribe to CodeOfaNinja now for FREE!

#3 Thank You!

Please share this post if you think this is a useful PHP CRUD Tutorial. We hope you mastered how to create, read, update and delete database records and more. Thanks for learning here in codeofaninja.com!