Chinaunix首页 | 论坛 | 博客
  • 博客访问: 6684626
  • 博文数量: 1159
  • 博客积分: 12444
  • 博客等级: 上将
  • 技术积分: 12570
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-13 21:34
文章分类

全部博文(1159)

文章存档

2016年(126)

2015年(350)

2014年(56)

2013年(91)

2012年(182)

2011年(193)

2010年(138)

2009年(23)

分类: Web开发

2016-03-16 21:40:43




Previously, we have learned how to program . Today, we will learn how to do CRUD with AngularJS, PHP and MySQL.

Welcome to the fifth part of the series. I’m happy to see you here, I love to see a person like you who has a great desire for learning!

I highly recommend studying the previous tutorials first before proceeding here. But if you think you can take this one, then go on.

This tutorial will focus on creating, reading, updating, deleting and searching database records. We will do it using a , PHP and MySQL.

As for the user interface, instead of , we will use – a modern responsive front-end framework based also on Google’s .


jQuery will also help us a little bit with modals. PDO and OOP will help us with the PHP part.

This will lead to other useful features like pagination, CSV downloads and more.

Contents of this post will include:

1.0 AngularJS CRUD Example PHP – Output

2.0 File Structure

3.0 Database table and connection
3.1 Create the database table
3.2 Dump sample data on the table
3.3 PHP script to connect to database

4.0 Put assets inside certain directories
4.1 Put AngularJS and jQuery libraries in “libs/js/” folder
4.2 Put Materialize CSS framework in “libs/css/” folder

5.0 Create “objects” folder with product.php object file
5.1 Basic code for the “product” class

6.0 Make use of your HTML coding skills
6.1 Create basic HTML code structure for index.php
6.2 Add custom CSS
6.3 Put the most important DIV tag

7.0 Create or insert data using AngularJS in PHP
7.1 HTML button to show the “create product HTML form”
7.2 HTML code of “create product form”
7.3 AngularJS Basic Code
7.4 AngularJS “showCreateForm” function to show “create product form”
7.5 AngularJS “clearForm” function to remove any form values that exists
7.6 AngularJS “createProduct” function
7.7 PHP code to create a record
7.8 Object code to create a record
7.9 Output should look like this

8.0 Read data using AngularJS in PHP
8.1 Display list of data in table
8.2 AngularJS code to read records
8.3 PHP script to read records
8.4 Object code to read records
8.5 Output should look like this

9.0 Update data using AngularJS in PHP
9.1 AngularJS code to read details of record to be edited
9.2 PHP script to read details of a record
9.3 Object code to read single record
9.4 AngularJS code to update a record
9.5 PHP script to update a record
9.6 Object code to update a record
9.7 Output should look like this

10.0 Delete data using AngularJS in PHP
10.1 AngularJS code to delete a record
10.2 PHP script to delete a record
10.3 Object code to delete a record
10.4 Output should look like this

11.0 What People Say About This Code?

12.0 Download Source Code

13.0 Some Notes

1.0 AngularJS CRUD Example PHP – Output

1.1 LEVEL 1 Source Code Output

To see the LEVEL 1 full list of features, go to section 12.1 below.

1.2 LEVEL 2 Source Code Output

To see the LEVEL 2 full list of features, go to section 12.2 below.

1.3 LEVEL 3 Source Code Output

To see the LEVEL 3 full list of features, go to section 12.3 below.

2.0 File Structure

Knowing the file structure will give us an overview of what PHP files do we need to create and where the assets should be placed.

0-angular-js-php-crud-file-structure

3.0 Database structure and connection

We have to create a database, then a table with the following table structure, and a PHP file that we will use for database connection.

3.1 Create the database table

Run the following SQL code on your PhpMyAdmin. This is to create our database table. By the way, the database name we used in this tutorial was named “phpajaxcrudlevel1”.

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

CREATE TABLE IF NOT EXISTS `products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(512) NOT NULL,
  `description` text NOT NULL,
  `price` 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=64 ;

3.2 Dump sample data on the table

Run the following SQL code on your PhpMyAdmin again, this will pre-insert 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, 'LG Optimus 4X HD P880 Black', 'Display - True HD-IPS LCD - 720 x 1280 pixels, 4.7 inches. Internal Memory - 16 GB storage (12 GB user available), 1 GB RAM. Camera - 8 MP, 3264x2448 pixels, autofocus, LED flash', 309, '2014-06-01 01:12:26', '2014-05-31 17:12:26'),
(2, 'Motorola Google Nexus 6, Midnight Blue 32GB', 'The stunning 6 inch Quad HD display is great for movies, videos, gaming, e-books, and surfing the Web, and the Nexus 6 provides exceptional battery life.', 400, '2014-06-01 01:12:26', '2014-05-31 17:12:26'),
(3, 'Samsung Galaxy S4 i9500 16GB', 'Make your life richer, simpler, and more fun. As a real life companion, the new Samsung GALAXY S4 helps bring us closer and captures those fun moments when we are together. Each feature was designed to simplify our daily lives. Furthermore, it cares enough to monitor our health and well being.', 600, '2014-06-01 01:12:26', '2014-05-31 17:12:26'),
(6, 'Bench Men''s Bench Spokes Slim T-Shirt', 'Make their heads spin by rollin'' through with swag to spare. Cotton-poly heather blend provides for a soft, comfortable wear. Screen printed Bench graphics on front. Slim fitting for modern appeal. Contrast topstitching along shoulders. Ribbed crew neck. Short sleeves', 14, '2014-06-01 01:12:26', '2014-05-31 02:12:21'),
(7, 'HP ZBook 17 Mobile Business Workstation', 'Feel the power! Take performance to a new level with the HP ZBook 17 with Intel''s quad core CPU and 4GB GDDR5 Nvidia Quadro graphics.  Project a professional image at the office, client meetings, and on the road without sacrificing durability in a stylish chassis.', 5149, '2014-06-01 01:13:45', '2014-05-31 02:13:39'),
(8, 'Samsung Galaxy Tab 4', 'Ideal for watching HD movies, playing games, browsing the web, or reading, the Samsung Galaxy Tab 4 features a 10.1-inch, 1280x800 resolution screen, so you experience rich graphics, bright colors, and crisp text.', 210, '2014-06-01 01:14:13', '2014-05-31 02:14:08'),
(9, 'Spalding Men', 'Right from the beginning, it was all about being first, being the best???being what others could only dream of becoming. Founded by Boston Red Stockings pitcher A.G. Spalding in 1876, Spalding has become a leader of innovation and quality in the sporting goods industry.', 49, '2014-06-01 01:18:36', '2014-05-31 02:18:31'),
(10, 'Sony Smart Watch 3', 'Contextually aware and smart, Android Wear gives you useful information at a glance and responds to your voice, feeding you relevant and specific information as you move.', 194, '2014-06-06 17:10:01', '2014-06-05 18:09:51'),
(11, 'Huawei SnapTo', 'Support all GSM 4G LTE Networks ( T-Mobile, AT&T, Straight Talk, NET10, etc.). 75% screen-body ratio and a stylish, leather-texture finish battery cover with a slim design make the phone compac', 179, '2014-06-06 17:11:04', '2014-06-05 18:10:54'),
(12, 'Abercrombie Men''s Lake Arnold Blazer', '100% Gabardine wool imported from Italy. Classic collegiate blazer with heritage A&F crest at left chest pocket. Front pockets with fold-over flaps.', 25, '2014-06-06 17:12:21', '2014-06-05 18:12:11');

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

3.3 PHP script to connect to database

Create a folder named “config” and inside it, create a database.php file with the following code. It answers how to connect to MySQL database with PDO?

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;
	}
}
?>

4.0 Put assets inside certain directories

4.1 Put AngularJS and jQuery libraries in “libs/js/” folder

and libraries and put it in “libs/js/” folder. This will enable us to use AngularJS and jQuery libraries even if we are offline.

4.2 Put Materialize CSS framework in “libs/css/” folder

framework and put it in “libs/css/” folder. This will enable us to use Material Design even if we are offline.

5.0 Create “objects” folder with product.php object file

The product.php file is located inside the “objects” folder. Put the following basic code for the “product” class.

conn = $db;
    }
}

6.0 Make use of your HTML coding skills

6.1 Create basic HTML code structure for index.php

Create the index.php file. This is the only page the user has to interact with. Make it ready for AngularJS, Material Design and jQuery by including the necessary library sources.








	Read Products


	
	
	
	
	










// angular js codes will be here

// jquery codes will be here

6.2 Add custom CSS

Put this code before the end “head” tag. We use some custom CSS to make our user interface look better.


.width-30-pct{
	width:30%;
}

.text-align-center{
	text-align:center;
}

.margin-bottom-1em{
	margin-bottom:1em;
}

6.3 Put the most important DIV tag

Inside this “div” tag is where every main content of the page will be loaded. Add the following code after the opeing “body” tag.

Products

7.0 Create or insert data using AngularJS in PHP

7.1 HTML button to show the “create product HTML form”

Put the following code under the “h4” tag in section 6.3, it will make a floating red button located at the lower right corner of the page.


7.3 AngularJS Basic Code

Put the following AngularJS code inside the “script” tag of section 6.1 above.

var app = angular.module('myApp', []);
app.controller('productsCtrl', function($scope, $http) {
	// more angular JS codes will be here
});

7.4 AngularJS “showCreateForm” function to show “create product form”

Put the following code inside the app.controller curly braces in section 7.3 above.

$scope.showCreateForm = function(){
	// clear form
	$scope.clearForm();
	
	// change modal title
	$('#modal-product-title').text("Create New Product");
	
	// hide update product button
	$('#btn-update-product').hide();
	
	// show create product button
	$('#btn-create-product').show();
	
}

7.5 AngularJS “clearForm” function to remove any form values that exists

Put the following code under the “showCreateForm” function code in section 7.4 above.

// clear variable / form values
$scope.clearForm = function(){
	$scope.id = "";
	$scope.name = "";
	$scope.description = "";
	$scope.price = "";
}

7.6 AngularJS “createProduct” function

The following code is triggered when the “Create Product” button on the modal or pop up form was clicked.

// create new product 
$scope.createProduct = function(){
		
	// fields in key-value pairs
	$http.post('create_product.php', {
			'name' : $scope.name, 
			'description' : $scope.description, 
			'price' : $scope.price
		}
	).success(function (data, status, headers, config) {
		console.log(data);
		// tell the user new product was created
		Materialize.toast(data, 4000);
		
		// close modal
		$('#modal-product-form').closeModal();
		
		// clear modal content
		$scope.clearForm();
		
		// refresh the list
		$scope.getAll();
	});
}

7.7 PHP code to create a record

Create a new file with a name “create_product.php”, it will receive all the data inputted by the user. It will also insert the data to the database with the help of the object code in section 7.8 below. Put the following code inside it.

getConnection();

// instantiate product object
include_once 'objects/product.php';
$product = new Product($db);

// get posted data
$data = json_decode(file_get_contents("php://input")); 

// set product property values
$product->name = $data->name;
$product->price = $data->price;
$product->description = $data->description;
$product->created = date('Y-m-d H:i:s');
	
// create the product
if($product->create()){
	echo "Product was created.";
}

// if unable to create the product, tell the user
else{
	echo "Unable to create product.";
}
?>

7.8 Object code to create a record

In your objects/product.php, add the following code to create a database record.

// create product
function create(){
	
	// query to insert record
	$query = "INSERT INTO 
				" . $this->table_name . " 
			SET 
				name=:name, price=:price, description=:description, created=:created";
	
	// prepare query
	$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));

	// bind values
	$stmt->bindParam(":name", $this->name);
	$stmt->bindParam(":price", $this->price);
	$stmt->bindParam(":description", $this->description);
	$stmt->bindParam(":created", $this->created);
	
	// execute query
	if($stmt->execute()){
		return true;
	}else{
		echo "
";
			print_r($stmt->errorInfo());
		echo "
"; return false; } }

7.8 Output should look like this

1-angular-js-php-crud-create-product

8.0 Read data using AngularJS in PHP

8.1 Display list of data in table

We will put the following code under the “h4” tag of our index.php

  
ID Name Description Price Action
{{ d.id }} {{ d.name }} {{ d.description }} {{ d.price }}

8.2 AngularJS code to read records

The following code will be inside the AngularJS app.controller curly braces.

// read products
$scope.getAll = function(){
	$http.get("read_products.php").success(function(response){
		$scope.names = response.records;
	});
}

8.3 PHP script to read records

Create a new file named read_products.php, it will retrieve records from the database. The code will look like the following.

getConnection();

// initialize object
$product = new Product($db);

// query products
$stmt = $product->readAll();
$num = $stmt->rowCount();

// check if more than 0 record found
if($num>0){
	
	$data="";
	$x=1;
	
	// retrieve our table contents
	// fetch() is faster than fetchAll()
	// 
	while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
		// extract row
		// this will make $row['name'] to
		// just $name only
		extract($row);
		
		$data .= '{';
			$data .= '"id":"'  . $id . '",';
			$data .= '"name":"'   . $name . '",';
			$data .= '"description":"'   . html_entity_decode($description) . '",';
			$data .= '"price":"' . $price . '"';
		$data .= '}'; 
		
		$data .= $x<$num ? ',' : ''; 
		
		$x++;
	}
}

// json format output
echo '{"records":[' . $data . ']}';
?>

8.4 Object code to read records

Put the following code in our objects/product.php file.

// read products
function readAll(){

	// select all query
	$query = "SELECT 
				id, name, description, price, created 
			FROM 
				" . $this->table_name . " 
			ORDER BY 
				id DESC";

	// prepare query statement
	$stmt = $this->conn->prepare( $query );
	
	// execute query
	$stmt->execute();
	
	return $stmt;
}

8.5 Output should look like this

Now we can view the product list and try the search feature.

2-angular-js-php-crud-read-products

9.0 Update data using AngularJS in PHP

9.1 AngularJS code to read details of record to be edited

The following code will help put the details of record to be edited to our HTML form.

// retrieve record to fill out the form
$scope.readOne = function(id){
	
	// change modal title
	$('#modal-product-title').text("Edit Product");
	
	// show udpate product button
	$('#btn-update-product').show();
	
	// show create product button
	$('#btn-create-product').hide();
	
	// post id of product to be edited
	$http.post('read_one.php', {
		'id' : id 
	})
	.success(function(data, status, headers, config){
		
		// put the values in form
		$scope.id = data[0]["id"];
		$scope.name = data[0]["name"];
		$scope.description = data[0]["description"];
		$scope.price = data[0]["price"];
		
		// show modal
		$('#modal-product-form').openModal();
	})
	.error(function(data, status, headers, config){
		Materialize.toast('Unable to retrieve record.', 4000);
	});
}

9.2 PHP script to read details of a record

Create a file named read_one.php and put the following code. Section 9.1 above will not work without this.

getConnection();

// prepare product object
$product = new Product($db);

// get id of product to be edited
$data = json_decode(file_get_contents("php://input"));     

// set ID property of product to be edited
$product->id = $data->id;

// read the details of product to be edited
$product->readOne();

// create array
$product_arr[] = array(
	"id" =>  $product->id,
	"name" => $product->name,
	"description" => $product->description,
	"price" => $product->price
);

// make it json format
print_r(json_encode($product_arr));
?>

9.3 Object code to read single record

Put the following code inside our objects/product.php file.

// used when filling up the update product form
function readOne(){
	
	// query to read single record
	$query = "SELECT 
				name, price, description  
			FROM 
				" . $this->table_name . " 
			WHERE 
				id = ? 
			LIMIT 
				0,1";

	// prepare query statement
	$stmt = $this->conn->prepare( $query );
	
	// bind id of product to be updated
	$stmt->bindParam(1, $this->id);
	
	// execute query
	$stmt->execute();

	// get retrieved row
	$row = $stmt->fetch(PDO::FETCH_ASSOC);
	
	// set values to object properties
	$this->name = $row['name'];
	$this->price = $row['price'];
	$this->description = $row['description'];
}f

9.4 AngularJS code to update a record

The following code will be triggered when the “Save Changes” button in the modal was clicked. Put it inside the app.controller curly braces.

// update product record / save changes
$scope.updateProduct = function(){
	$http.post('update_product.php', {
		'id' : $scope.id,
		'name' : $scope.name, 
		'description' : $scope.description, 
		'price' : $scope.price
	})
	.success(function (data, status, headers, config){             
		// tell the user product record was updated
		Materialize.toast(data, 4000);
		
		// close modal
		$('#modal-product-form').closeModal();
		
		// clear modal content
		$scope.clearForm();
		
		// refresh the product list
		$scope.getAll();
	});
}

9.5 PHP script to update a record

Create a new file and name it “update_product.php”, it will have the following code. Code in section 9.4 will not work without it.

getConnection();

// prepare product object
$product = new Product($db);

// get id of product to be edited
$data = json_decode(file_get_contents("php://input"));     

// set ID property of product to be edited
$product->id = $data->id;

// set product property values
$product->name = $data->name;
$product->price = $data->price;
$product->description = $data->description;

// update the product
if($product->update()){
	echo "Product was updated.";
}

// if unable to update the product, tell the user
else{
	echo "Unable to update product.";
}
?>

9.6 Object code to update a record

Add the following code in our objects/product.php file.

// update the product
function update(){

	// update query
	$query = "UPDATE 
				" . $this->table_name . " 
			SET 
				name = :name, 
				price = :price, 
				description = :description 
			WHERE
				id = :id";

	// prepare query statement
	$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));

	// bind new values
	$stmt->bindParam(':name', $this->name);
	$stmt->bindParam(':price', $this->price);
	$stmt->bindParam(':description', $this->description);
	$stmt->bindParam(':id', $this->id);
	
	// execute the query
	if($stmt->execute()){
		return true;
	}else{
		return false;
	}
}

9.7 Output should look like this

When you clicked an “Edit” button in the product list, you should see the modal with form data of record to be edited.

3-angular-js-php-crud-update-product

10.0 Delete data using AngularJS in PHP

10.1 AngularJS code to delete a record

Put the following code inside the app.controller part of our AngularJS code.

// delete product
$scope.deleteProduct = function(id){
	
	// ask the user if he is sure to delete the record
	if(confirm("Are you sure?")){
		// post the id of product to be deleted
		$http.post('delete_product.php', {
			'id' : id
		}).success(function (data, status, headers, config){
			
			// tell the user product was deleted
			Materialize.toast(data, 4000);
			
			// refresh the list
			$scope.getAll();
		});
	}
}

10.2 PHP script to delete a record

Create a new file, name it “delete_product.php” and put the following code inside it.

getConnection();

// prepare product object
$product = new Product($db);

// get product id
$data = json_decode(file_get_contents("php://input"));     

// set product id to be deleted
$product->id = $data->id;

// delete the product
if($product->delete()){
	echo "Product was deleted.";
}

// if unable to delete the product
else{
	echo "Unable to delete object.";
}
?>

10.3 Object code to delete a record

Put the following code inside our objects/product.php file.

// delete the product
function delete(){

	// delete query
	$query = "DELETE FROM " . $this->table_name . " WHERE id = ?";
	
	// prepare query
	$stmt = $this->conn->prepare($query);
	
	// bind id of record to delete
	$stmt->bindParam(1, $this->id);

	// execute query
	if($stmt->execute()){
		return true;
	}else{
		return false;
	}
}

10.4 Output should look like this

When a delete button was clicked, it will show a confirmation pop up. When the user clicked “Ok”, a toast message will appear confirming the deletion of a record.

4-angular-js-php-crud-delete-product

11.0 What People Say About This Code?

We tried to share this post online and the following are what people think.

testimonial-1-angularjs-crud-example-php

testimonial-2-angularjs-crud-example-php

12.0 Source Code Download

You can get the source code by following the whole, well detailed tutorial above. But isn’t it more convenient if you can just download the complete source code we used, and play around it?

There’s a small fee in getting the complete source code, it is small compared to the:

? Value or skill upgrade it can bring you, or YES
? Income you can get from your website project or business. YES
? Precious time you save. YES

For a limited time, I will give you the source code for a low price. DOWNLOAD THE SOURCE CODE LEVEL you desire by clicking its the BUY button below.

阅读(4100) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~