PHP for Beginners – Part 5

by  
Share:
PHP for Beginners

Hey Guys!  This is the last part of the tutorial series. In this tutorial you will learn to create a database, connect your database with PHP, and query the database (MySQL) using SQL to Create, retrieve, update, delete (CRUD) records. If you want to learn SQL you can learn from w3schools. After the end of this tutorial series you will surely not be a beginner in PHP language.

 Let’s get started with creating a database first. open phpMyAdmin, and create a database  say “MyDatabase“.  Then create a table named “players” and insert some data so you can play with them. If you have trouble creating database through PhpMyAdmin refer to this video Installing xampp on windows Machine. Given below is the SQL script  for creating a table and inserting some records.

CREATE TABLE `players` (
    `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, 
    `name` VARCHAR(255) NOT NULL, 
    `age` INT NOT NULL, `club` VARCHAR(255) NOT NULL
)

INSERT INTO `players` (`id`, `name`, `age`, `club`) VALUES 
(NULL, 'David Beckham', '38', 'PSG'), 
(NULL, 'John Terry', '35', 'Chelsea'), 
(NULL, 'Lionel Messi', '26', 'FC Barcelona'), 
(NULL, 'Cristiano Ronaldo', '28', 'Real Madrid FC'), 
(NULL, 'Neymar da Silva', '21', 'FC Barcelona'), 
(NULL, 'Steven Gerrard', '33', 'Liverpool'), 
(NULL, 'Wayne Rooney', '27', 'Manchester United'), 
(NULL, 'Robin van Persie', '29', 'Manchester United'), 
(NULL, 'Rio Ferdinand', '34', 'Manchester United'), 
(NULL, 'Ryan Giggs', '39', 'Manchester United');

How to include one file within another file

<?php
include("somefile.php");
include_once("somefile.php");
require("somefile.php");
require_once("somefile.php");
?>

There are 4 types of function that we can choose for including a file in another file:
  • include – It will always include the file, irrespective if file was included earlier,  gives a warning if could not find the file and continues the script
  • include_once – – It will include the file only if file was not included earlier, gives a warning if could not find the file and continues the script
  • require – It will always include the file, irrespective if file was included earlier,  stops the script if file not found.
  • require_once – It will include the file only if file was not included earlier,  stops the script if file not found.

If you have some critical file that is very necessary for the script, like database connection file, use require function. If you have some template file for html designing purpose you can use include function. If you want to include a file which has common function use include_once or including a function file multiple time will gives “function redeclare” error.

I have made a mini project that will insert, edit, delete and display data from the database. Have a look at the screenshots and download the code as well.

Database connection using PDO and error reporting

Create a file config.php that will be included in each page. It will have error reporting method, database connection and error message functions.

<?php

// display all error except deprecated and notice  
error_reporting( E_ALL & ~E_DEPRECATED & ~E_NOTICE );
// turn on output buffering 
ob_start();

define('DB_DRIVER', 'mysql');
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASSWORD", "");
define("DB_DATABASE", "testdatabase");

require("functions.php");

// basic options for PDO 
$dboptions = array(
    PDO::ATTR_PERSISTENT => FALSE,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);

//connect with the server
try {
    $DB = new PDO(DB_DRIVER . ':host=' . DB_HOST . ';dbname=' . DB_DATABASE, DB_USER, DB_PASSWORD, $dboptions);
} catch (Exception $ex) {
    printErrorMessage($ex->getMessage());
    die;
}

?>

Create a php file functions.php file which has error messaging functions.
<?php 
function printErrorMessage($str) {
	echo '<div style="width:50%; margin:0 auto; border:2px solid #F00;padding:2px; color:#000; margin-top:10px; text-align:center;">'.$str.'</div>';	
}
function printSuccessMessage($str) {
	echo '<div style="width:50%; margin:0 auto; border:2px solid #06C;padding:2px; color:#000; margin-top:10px; text-align:center;">'.$str.'</div>';	
}

?>

Creating landing page with listing and search filter

Create a php file index.php file which will be the home page of the project. It is the landing page of the project. Let start creating it step by step. Start with basic template structure and including the database connection file.

<?php
// include the basic config file
require("config.php");
?>
<!DOCTYPE html>
<html>
<head>
  <link rel="icon" href="favicon.ico" type="image/x-icon" />
  <title>Database Sample Script - aarafacademy.com</title>
  <link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
  <div id="container">
    <div id="body">
      <header>
        <div class="mainTitle" >Sample Database Script :: HOMEPAGE</div>
      </header>
      <article>
         body of the page
      </article>
      <footer>
        footer of the page
      </footer>
    </div>
  </div>

</body>
</html>

Fetching players records from database and display them in a table listing with edit and delete action links.
<?php 
$sql = "SELECT * FROM players WHERE 1";
try {
  $stmt = $DB->prepare($sql);
  $stmt->execute();
  $results = $stmt->fetchAll();
} catch (Exception $ex) {
  echo $ex->getMessage();
}
?>

<table id="tableshow">
<tr>
  <th style="text-align: left;">Name</th>
  <th>Age</th>
  <th>Club</th>
  <th>Action</th>
</tr>
<?php
if (count($results) > 0) {
?>
<?php
	// display all players
	foreach ($results as $rs) {
	?>
	<tr>
	  <td style="text-align: left;"><?php echo stripslashes($rs["name"]) ?></td>
	  <td><?php echo stripslashes($rs["age"]) ?></td>
	  <td><?php echo stripslashes($rs["club"]) ?></td>
	  <td><a href="edit.php?id=<?php echo ($rs["id"]) ?>">Edit</a>&nbsp;&nbsp; <a href="delete.php?id=<?php echo ($rs["id"]) ?>" onClick="javascript:return confirm('Are you sure you want to delete?');" >Delete</a></td>
	</tr>
	<?php
	} 
} else {
  echo '<tr><td colspan="4">No Records Found</td></tr>';
}
?>
</table>

Adding a search feature, so user can search players by name. Create a form and add a text field. Set the form method to GET method.
<table>
<tr>
  <td>
    <div style="text-align:left;">
    <form method="get" name="searchForm" action="<?php echo $_SERVER['PHP_SELF']; ?>">
      <label ><strong>Search player by name:</strong> <input type="text" name="s" value="<?php echo $_GET["s"]; ?>" ></label> &nbsp;
      <input type="submit" value="Search" />
    </form>
    </div>
  </td>
</tr>
</table>

When the user types a search keyword and submits the form, then the server must process the form accordingly, query the database using that keyword and display the result.
<?php
// get the search paramenter
$s = trim($_GET["s"]);
if ($s <> "") {
  $seachSQL = " AND name LIKE :search ";
}
$sql = "SELECT * FROM players WHERE 1 $seachSQL";
try {
  $stmt = $DB->prepare($sql);
  if ($s <> "") {
    $stmt->bindValue(":search", "%" . $s . "%");
  }
  $stmt->execute();
  $results = $stmt->fetchAll();
} catch (Exception $ex) {
  echo $ex->getMessage();
}
?>

Adding a new record in database using form

Create a new page insert.php which will have a form containing text fields for name, age and club. User will add values in the form and submit it. The server will then process the form and saves the value in the database. Lets get started by creating the form. Set the form method as POST which is secure and can transmit more values than GET method.

<form method="post" action="" name="form1">
<table style="margin:0 auto;width:280px;padding-top:30px;">
	<tr>
		<td>Player name: </td>
		<td><input type="text" name="p_name" /> </td>
	</tr>
	<tr>
		<td>Player Age: </td>
		<td><input type="text" name="p_age" /> </td>
	</tr>
	<tr>
		<td>Player Club: </td>
		<td> <input type="text" name="p_club" /> </td>
	</tr>
	<tr>
		<td></td>
		<td> <input type="submit" name="sub" value="Save" /> </td>
	</tr>       
</table>
</form

When the user submits the form add this piece of code at the top of the page (insert.php) . Do some basic data validation and then try to insert the data in the database.
<?php
if (isset($_REQUEST["sub"])) {

    $p_name = trim(($_REQUEST["p_name"]));
    $p_age = trim(($_REQUEST["p_age"]));
    $p_club = trim(($_REQUEST["p_club"]));
    if ($p_name <> "" && $p_age <> "" && $p_club <> "") {
        $sql = "INSERT INTO `players` (`name`, `age`, `club`) VALUES (:n, :a, :c);";

        try {
            $stmt = $DB->prepare($sql);
            $stmt->bindValue(":n", $p_name);
            $stmt->bindValue(":a", $p_age);
            $stmt->bindValue(":c", $p_club);
            $stmt->execute();

            if ($stmt->rowCount()) {
                printSuccessMessage("Record added successfully");
            } else {
                printErrorMessage("could not insert into database. Please try again");
            }
        } catch (Exception $ex) {
            printErrorMessage($ex->getMessage());
        }

    } else {
        printErrorMessage("All fields are mandatory");
    }
}
?>

Updating an existing record

Create a new page edit.php which will have a similar form like we create in add page (insert.php). When user select a record ( from listing) to edit/update, it will have its unique ID ( primary key ) in the query string of the page (edit.php?id=1). Using that ID you can fetch the records from the database.

<?php
$id = intval(trim($_REQUEST["id"]));
$sql = "SELECT * FROM players WHERE id = :id";

try {
	$stmt = $DB->prepare($sql);
	$stmt->bindValue(":id", $id);
	$stmt->execute();
	$rs = $stmt->fetchAll();

   
} catch (Exception $ex) {
	printErrorMessage($ex->getMessage());
}
?>

Displaying the records in the form field. Store the ID in a hidden field so when user update the form it will pass that ID using POST method.
<form method="post" action="" name="editform">
<input type="hidden" value="<?php echo $id; ?>" name="pid" />
<table>
	<tr>
		<td>Player name: </td>
		<td><input type="text" name="p_name" value="<?php echo stripslashes($rs[0]["name"]) ?>"  /> </td>
	</tr>
	<tr>
		<td>Player Age: </td>
		<td><input type="text" name="p_age" value="<?php echo stripslashes($rs[0]["age"]) ?>" /> </td>
	</tr>
	<tr>
		<td>Player Club: </td>
		<td> <input type="text" name="p_club"  value="<?php echo stripslashes($rs[0]["club"]) ?>" /> </td>
	</tr>
	<tr>
		<td></td>
		<td> <input type="submit" name="sub" value="Update" /> </td>
	</tr>       
</table>
</form>

Finally when user submits the form after changing the value, the server must process the form values and update the database row.
<?php
if (isset($_REQUEST["sub"])) {

    $pid = intval(trim($_REQUEST["pid"]));
    $p_name = trim($_REQUEST["p_name"]);
    $p_age = trim($_REQUEST["p_age"]);
    $p_club = trim($_REQUEST["p_club"]);
    if ($p_name <> "" && $p_age <> "" && $p_club <> "" && $pid <> "") {
        $sql = "UPDATE `players` SET `name` = :n, `age` = :a, `club` = :c WHERE `id` = :id";
        try {
            $stmt = $DB->prepare($sql);
            $stmt->bindValue(":n", $p_name);
            $stmt->bindValue(":a", $p_age);
            $stmt->bindValue(":c", $p_club);
            $stmt->bindValue(":id", $pid);
            $stmt->execute();

            if ($stmt->rowCount()) {
                printSuccessMessage("Record updated successfully");
            } else {
                printErrorMessage("Could not update Record. Please try again");
            }
        } catch (Exception $ex) {
            printErrorMessage($ex->getMessage());
        }
    } else {
        printErrorMessage("All fields are mandatory");
    }
}
?>

Deleting a record from database

Create a new page delete.php which will use the same technique as edit.php. The record ID will be passed to delete.php using query string ( delete.php?id=4) and then using PHP code make a database call to delete that record.

<?php
$id = intval(trim($_REQUEST["id"]));
$sql = "DELETE FROM players WHERE id = :id";
try {
    $stmt = $DB->prepare($sql);
    $stmt->bindValue(":id", $id);
    $stmt->execute();

    if ($stmt->rowCount()) {
        printSuccessMessage("Record deleted successfully");
    } else {
        printErrorMessage("Could not delete record. Please try again");
    }
} catch (Exception $ex) {
    printErrorMessage($ex->getMessage());
}
?>

Share to download the Source Codes for FREE!
We're glad to give free downloads, but we need your love to carry on making that.
Please support us by sharing the page.

In case you are not tired have a look at this article 35 Important interview questions with answers for php freshers.

Get the latest updates directly in your inbox for FREE: Subscribe here

Share your feedback / let me know your doubts regarding this tutorial in the comment box given below.

Share:
Hasan

Shahrukh Khan (Hasan)

A software engineer who's a die-hard coder, blogger, dreamer and mentor with years of expertise in web development. Know more...

Related Posts

Khurshid Md Anwar on

Very good PHP tutorial, I have learnt a lot from this tutorial.

Reply
php tutorials on

Thanks for this useful post. check this website, A php tutorials that covers all the basics of PHP with examples help to learn php language for Beginners Online.Great php tutorials tips for programming. It can help better for php developers.

Reply
vans clothing sale on

Hello there, I do think your website might be having browser compatibility
issues. When I take a look at your site in Safari, it
looks fine however when opening in I.E., it’s got some overlapping issues.
I just wanted to give you a quick heads up! Aside from that, great blog!:
\

Reply
Shahrukh Khan on

Thanks will check onto that.

Reply
Diksha on

Thank you very much for all these tutorials!!!

Reply
Deepti on

Thanks for such valuable tutorials..Wonderful Job!!

Reply
Shahrukh Khan on

Thanks

Reply
Bruce on

Thank you for preparing the PHP tutorials. They will help me get started on publishing a database that I’m working on.

My only criticism is the jump from tutorial 4 to tutorial 5 was a HUGE step. May I suggest a 4.5 tutorial that:
1. provides more background on all the new PHP commands that will be used in tutorial 5
2. outlines the structure and strategy for composing the separate PHP files and forms that will be used
Additionally, include more inbedded comments within tutorial 5 explaining the commands/functions and the meaning of each of the function arguments.

Please take the criticism in the spirit in which is is being offered; to be constructive in aiding truly raw beginners on this subject. I, myself, am a terrible instructor and often find it hard to teach others and welcome feedback on where I miss the mark in providing easy to follow instructions.

Thank you again for your efforts. Your passion for helping others learn software is obvious and I appreciate what you’ve put together over these past years.

Reply
Shahrukh Khan on

Hi Bruce.

Thanks for being critical and I also appreciate your valuable feedback. I will sure look into it and either try to revise it or make another tutorial and some other study material based on it.

Best of luck to you as well.

Reply
LearnQuickly.In on

Thanks for this handy post. check this website, This tutorial that covers all the basics of PHP with examples which will help for beginners and experienced learner online.

Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.