Create simple application in php

How To Develop A PHP MYSQL Web App (Simple Example)

Welcome to a quick tutorial on how to develop a simple web application with PHP and MySQL. When it comes to building a full-stack web application, some beginners go blank and do not know where to get started.

Web applications are developed in stages, in a step-by-step manner.

  1. Gather the requirements – Know what the users want, what the application should do, what the goals are.
  2. Design the structure of the database.
  3. Build the core PHP scripts and libraries.
  4. Design the interface, build the pages with HTML, CSS, Javascript.
  5. Finally, test and deploy the web application.

Yes, some of you may have already heard of it, this is called the software development life cycle (SDLC). One does not tackle a project without any plans but takes it apart piece by piece. Let us walk through the development cycle of a simple example to-do list in this guide – Read on!

Читайте также:  Php array key and value to string

TABLE OF CONTENTS

PHP WEB APP DEVELOPMENT

All right, let us now get into the details of developing a simple “to-do” list in PHP and MYSQL – Step by step.

PART 1) GATHER THE REQUIREMENTS

This is the most important step that some people miss out on, thinking that it’s useless and a waste of time. Well, no. Big or small projects, it all starts with “boring planning”. Even for the smallest personal projects, we need to have a plan on “what to build” and “how to build”.

  • We need to create a simple to-do list.
  • The task list should be stored in a database.
  • There should be flags to indicate if a task is still “pending”, “done”, or “canceled”.
  • Have a page to manage (add, update, delete) the tasks.

PART 2) BUILD THE DATABASE

CREATE TABLE `todo` ( `todo_id` bigint(20) NOT NULL, `todo_task` text NOT NULL, `todo_status` tinyint(1) NOT NULL DEFAULT 0 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; ALTER TABLE `todo` ADD PRIMARY KEY (`todo_id`); ALTER TABLE `todo` MODIFY `todo_id` bigint(20) NOT NULL AUTO_INCREMENT;

Now that we are done with the planning and have a rough idea of the system, let’s move on to deal with the foundation of the project – The database tables. This should be straightforward enough:

  • todo_id The task ID, primary key.
  • todo_task Description of the task itself.
  • todo_status The current status of the task, 0 for pending, 1 for done, 2 for canceled.

Yep, that should be sufficient to cover the requirements of “keeping the tasks and tracking their status”.

PART 3) PHP LIBRARY

pdo = new PDO( "mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET, DB_USER, DB_PASSWORD, [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC ]); > // (B) DESTRUCTOR - CLOSE DATABASE CONNECTION function __destruct () < if ($this->stmt!==null) < $this->stmt = null; > if ($this->pdo!==null) < $this->pdo = null; > > // (C) HELPER - RUN SQL QUERY function query ($sql, $data) :void < $this->stmt = $this->pdo->prepare($sql); $this->stmt->execute($data); > // (D) SAVE TO-DO TASK function save ($task, $status, $id=null) < if ($id===null) < $sql = "INSERT INTO `todo` (`todo_task`, `todo_status`) VALUES (. )"; $data = [$task, $status]; >else < $sql = "UPDATE `todo` SET `todo_task`=?, `todo_status`=? WHERE `todo_id`=?"; $data = [$task, $status, $id]; >$this->query($sql, $data); return true; > // (E) GET ALL TASKS function getAll () < $this->query("SELECT * FROM `todo`"); return $this->stmt->fetchAll(); > // (F) DELETE TASK function del ($id) < $this->query("DELETE FROM `todo` WHERE `todo_id`=?", [$id]); return true; > > // (G) DATABASE SETTINGS - CHANGE TO YOUR OWN! define("DB_HOST", "localhost"); define("DB_NAME", "test"); define("DB_CHARSET", "utf8mb4"); define("DB_USER", "root"); define("DB_PASSWORD", ""); // (H) NEW TO-DO OBJECT $TODO = new ToDo();
  • (A, B, H) When $TODO = new ToDo() is created, the constructor automatically connects to the database. The destructor closes the connection.
  • (C) query() A simple helper function to run SQL queries.
  • (D to F) There are only 3 essential functions to cover the “manage to-do tasks”.
    • save() Add or update a task.
    • getAll() Get all to-do tasks.
    • del() Delete a task.

    Long story short, this library is quite literally just a collection of INSERT UPDATE DELETE SELECT SQL.

    PART 4) USER INTERFACE

    4A) HTML PAGE

    save($_POST["task"], $_POST["status"], (isset($_POST["id"])?$_POST["id"]:null)); > // (A2) DELETE TASK else < $pass = $TODO->del($_POST["id"]); > // (A3) SHOW RESULT echo "
    error ; echo "
    "; > ?> getAll(); if (count($tasks)!=0) < foreach ($tasks as $t) < ?> > ?>
  • (B & C) Straightforward. HTML forms to delete and add a task.
  • (D) We use the PHP library to get all tasks and display them in “nice HTML rows”.
  • (A) When add/update/delete task is submitted, we use the PHP library once again to update the database accordingly.

4B) CSS COSMETICS

* < font-family: Arial, Helvetica, sans-serif; box-sizing: border-box; >.notify < background: #ecefff; border: 1px solid #bfc4ff; padding: 5px; margin-bottom: 10px; >#tasks < max-width: 500px; >#tasks form < display: grid; grid-template-columns: 10% 60% 20% 10%; padding: 10px; background: #f7f7f7; border: 1px solid #ccc; margin-bottom: 10px; >#tasks input, #tasks select < box-sizing: border-box; padding: 10px; cursor: pointer; border: 0; >#tasks input[type=button], #tasks input[type=submit] < color: #fff; >#tasks input[type=button] < background: #a72020; >#tasks input[type=submit] < background: #577ed8; >#taskadd

As it is… Some CSS cosmetics to make things look better.

4C) THE JAVASCRIPT

Finally, a small snippet of necessary Javascript to handle the “delete task” HTML form.

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

SUPPORT

600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

That’s all for this example, and here is a small section on some extras and links that may be useful to you.

SOFTWARE DEVELOPMENT NEVER ENDS

  • Requirement – Add a timestamp to track when the task is last updated.
  • Database – Add a new new “updated” timestamp column.
  • PHP library – Update the functions to also include the timestamp.
  • To-do page – Show the timestamp somewhere.

Yes, that is running through the development cycle once again; It never ends and will continue to loop when new requirements pop up.

  • Software Development Life Cycle (SDLC) – Wikipedia
  • Create Read Update Delete (CRUD) – Wikipedia
  • How To Create a Simple CRUD Application With PHP MySQL – Code Boxx
  • Model–view–controller (MVC) – Wikipedia
  • Simple PHP MVC – Code Boxx
  • Rapid Application Development – Wikipedia

THE END

Thank you for reading, and we have come to the end of this guide. It may not be easy to develop a full-stack application at first, but break the project down into smaller parts, and you will be able to conquer them piece by piece. If you have anything to share, please feel free to comment below. Good luck and happy coding!

Источник

Write your first PHP application

In this tutorial we introduce you to writing and running a simple PHP application. We will learn some PHP syntax, how we can integrate HTML in a PHP file and how to run the application in a web browser.

Before we begin

Before you begin, you must have a PHP parser installed on your system.

If you don’t have an environment set up yet, please follow one of the links below before continuing.

Your first PHP application

First things first, if you haven’t started the web server yet, open the XAMPP Control and start the Apache web server module. Without it, we won’t be able to run our application.

Next, we need to create a file to hold the PHP code.

  1. Open your Atom IDE. In the Project Pane on the left, right-click on the PHPProjects folder and select New File.
  2. Name the file HelloWorld.php and press Enter or Return on your keyboard.

Write the code below into your HelloWorld.php file and save it by going to File > Save.

 In your web browser navigate to the url: localhost/PHPProjects/HelloWorld.php

You should see the words “Hello World” on the page.

If you gave your project folder or php file a different name, please make sure that reflects in the url, otherwise the PHP script won’t run.

Breakdown of your first PHP application

In this breakdown, we will go through the code line by line so you can have a basic understanding of the syntax of a PHP application.

Open and close tags

The open and close tags in PHP indicate a dedicated space between them for PHP code. PHP cannot parse code outside of these tags.

The interpreter will scan the document, looking for these tags. When it finds them, it will attempt to execute the code within.

Other types of code, such as HTML, is allowed within the document. Because of this, we explicitly tell the interpreter where the PHP code is written.

If there were no open and close tags, PHP scripts that contain other types of code could become confusing quickly and the interpreter might misinterpret conflicting code and break the application.

Comments

PHP allows us to document our code, and one of the ways we do that is with comments. Comments are completely ignored by the interpreter at runtime.

Single line comments are prefixed with two forward slashes // . Anything on that same line, after the forward slashes, will be ignored by the interpreter.

 If you’re working in an IDE, it will usually recolor comments into a grey color to indicate that the code is a comment.

The echo command statement

The echo statement in PHP is a command statement that will display whatever comes after it on the page.

 In this particular case we print the words “Hello World”, known as a string, on the page. The contents of a string are always enclosed within quotes.
 At the end of the command we write a semicolon operator ; . A semicolon is a statement terminator and indicates to the interpreter that this command is ended at this point.

As we’ve mentioned previously, PHP can be written alongside other languages, like HTML, in the same document.

When writing PHP in a document with HTML code, we must remember that the document must be a PHP type document with the .php extension.

If we write PHP code in a document with a .html extension, it will not be executed.

Quick HTML Intro

HTML is a markup language, it uses opening and closing tags to specify elements in a hierarchical fashion. Inside these elements we can specify text, links and images which will be shown on a webpage.

The following is an example of what an HTML tag pair looks like.

An open tag is written by using a keyword in between a less than and a greater than > symbol.

A close tag is written the same as an open tag but has a forward slash in front of the keyword.

 The most basic html document consists of , and tags. The head and body tags are nested inside the html tags.

Clear the PHP code we wrote earlier from the HelloWorld.php document and copy & paste the HTML below into the file.

Now that we have some HTML to work with we’ll write our PHP code inside of it. We want to write the same echo statement, but this time inside the tag in the body of the HTML.

In between the open and close tags, we simply write the same PHP code that we did in the very first example, only this time we write it all on one line.

When we refresh the webpage in the browser we can see that the text “Hello World” is now a heading, bigger and bold.

We have successfully written both a PHP only application and a PHP webpage.

Summary: Points to remember

  • PHP code will only be executed in a document with the .php extension.
  • PHP code will only be executed if it is wrapped in open and close PHP tags:
  • We can combine PHP with other languages like HTML by writing the HTML inside our .php document.

Источник

Оцените статью