Form AngularJS Insert MySQL

Page Submit Form

<html lang="fr" >
	<head>
		<meta charset="UTF-8">
	
		<meta name="viewport" content="width=device-width, initial-scale=1">
		
		<!-- Bootstrap CSS -->
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
	  
	  	<!-- Angular Material requires Angular.js Libraries -->
		<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.js"></script>
		<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-animate.js"></script>
		<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-aria.js"></script>
		<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-messages.js"></script>
	
		<!-- Angular Material Library -->
		<script src="https://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.js"></script>
	  
		<!-- Angular Material style sheet -->
		<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.css">
	</head>
	<body>
	
		<!-- HTML content -->  		
		<div ng-app="cocktailAddApp" ng-controller="httpPostCocktailAdd">
		
			<form class="form-horizontal" name="cocktailAddForm" ng-submit = "submitForm()" novalidate> <!-- novalidate = desactive HTML5 form and avoids conflicts -->
				
				<!--************************* COCKTAIL NAME **************************-->
				<div class="form-group" ng-class="{'has-error': cocktailAddForm.$dirty && cocktailAddForm.name_cocktail.$invalid, 'has-success': cocktailAddForm.name_cocktail.$valid}">
					<label class="col-md-3 control-label" for="name_cocktail">Name</label>
					<div class="col-md-4">
						<input ng-maxlength="50" required id="name_cocktail" type="text" class="form-control" name="name_cocktail" ng-model="userData.name_cocktail" />
						
						<!-- Error message name cocktail-->
						<span class="text-danger" ng-show="cocktailAddForm.name_cocktail.$error.maxlength">
						   Maximum 50 characters
						</span>		
					</div>
				</div>
				
				<!--************************* COCKTAIL RECIPE **************************-->
				<div class="form-group" ng-class="{'has-error': cocktailAddForm.$dirty && cocktailAddForm.recipe_cocktail.$invalid, 'has-success': cocktailAddForm.recipe_cocktail.$valid}">
					<label class="col-md-3 control-label" for="recipe_cocktail">Recipe</label>
					<div class="col-md-4">
						<textarea ng-maxlength="1000" required id="recipe_cocktail" type="text" class="form-control" name="recipe_cocktail" ng-model="userData.recipe_cocktail"></textarea>
						
						<!-- Error message recipe cocktail-->
						<span class="text-danger" ng-show="cocktailAddForm.recipe_cocktail.$error.maxlength">
						   Maximum 1000 characters
						</span>		
					</div>
				</div>
				
				<!--************************* COCKTAIL DECORATION **************************-->
				<div class="form-group" ng-class="{'has-error': cocktailAddForm.$dirty && cocktailAddForm.decoration_cocktail.$invalid, 'has-success': cocktailAddForm.decoration_cocktail.$valid}">
					<label class="col-md-3 control-label" for="decoration_cocktail">Decoration</label>
					<div class="col-md-4">
						<textarea ng-maxlength="1000" required id="decoration_cocktail" type="text" class="form-control" name="decoration_cocktail" ng-model="userData.decoration_cocktail"></textarea>
						
						<!-- Error message decoration cocktail-->
						<span class="text-danger" ng-show="cocktailAddForm.decoration_cocktail.$error.maxlength">
						   Maximum 1000 characters
						</span>		
					</div>
				</div>		
				
				<!--************************* SUBMIT **************************-->
				<div class="form-group">
					<div class="col-md-offset-3 col-md-9">
						<input type="submit" class="btn btn-default" value="Enregistrer" ng-disabled="cocktailAddForm.$invalid" />
					</div>
				</div>
				
			</form>
		</div>

		<!--  END HTML content -->
			//Form submit app
			var app = angular.module('cocktailAddApp', []);	
			
			app.controller('httpPostCocktailAdd', function($scope, $http) 
			{
				$scope.userData = 
				{
					name_cocktail: $scope.name_cocktail,
					recipe_cocktail: $scope.recipe_cocktail,
					decoration_cocktail: $scope.decoration_cocktail,
				};
			
				$scope.submitForm = function () 
				{
					$http(
					{ 
						method: 'post',
						url: 'http://192.168.16.90/cocktails/admin/api/v1/addCocktail.php',
						data: $scope.userData,
						headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
					})
					
					.success(function(data) 
					{
						if (data.errors) 
						{
							//Showing errors
							$scope.errorName = data.errors.name;
							$scope.errorUserName = data.errors.username;
							$scope.errorEmail = data.errors.email;
			            } 
						else 
						{
							$scope.message = data.message;
			            }
					});
				};
			});

					
		</script>
	  
	</body>
</html>

Page addCocktail.php

	//connexion DB + include constants
	require_once($_SERVER['DOCUMENT_ROOT'] . '/cocktails/inc/commun.php');

	if(isset($_POST) & !empty($_POST))
	{
		//getting posted data and decoding json
		$_POST = json_decode(file_get_contents('php://input'), true);
		
		$name_cocktail = $_POST['name_cocktail'];
		$recipe_cocktail = $_POST['recipe_cocktail'];
		$decoration_cocktail = $_POST['decoration_cocktail'];
		$date_add_cocktail = date("Y-m-d", strtotime("now"));
		
		//post datas values array
		$values = array(
				'name_cocktail'=>$name_cocktail,
				'recipe_cocktail'=>$recipe_cocktail,
				'decoration_cocktail'=>$decoration_cocktail,
				'date_add_cocktail'=>$date_add_cocktail
				);
		
		//PDO query
		$query = "INSERT INTO cocktails (name_cocktail, recipe_cocktail, decoration_cocktail, date_add_cocktail) VALUES ('".$name_cocktail."', '".$recipe_cocktail."', '".$decoration_cocktail."', '".$date_add_cocktail."');";
		
		//query preparation
		$stmt = $connexion->prepare($query);
		
		//query execution
		$stmt->execute($values);
	}

Infos

$valid : Indique si les règles de validation sont respectées pour l’élément actuel
$invalid : Indique si au moins une des règles de validation est violée pour l’élément actuel
$pristine : Indique si l’élément actuel n’a pas été modifié
$dirty : Indique si l’élément actuel a été modifié
$error. : Indique si la règle de validation est violée
Ces propriétés sont accessibles via :

nom du formulaire.propriété
nom du formulaire.nom du champ.propriété

Les règles de validation supportées de base sont :

[type= »email | number | month | url | … »]
[required= » »]
[ng-required= » »]
[min= » »]
[max= » »]
[ng-minlength= » »]
[ng-maxlength= » »]
[ng-pattern= » »]>

Bootstrap utilise les classes CSS “has-error” et “has-success” pour indiquer la validité de la saisie. Pour ajouter ces classes dynamiquement on utilise la directive “ng-class”
La classe CSS “has-error” sera défini si le formulaire est modifié et que le champ password est invalide (texte vide ou longueur inférieure à 6 caractères). La classe CSS “has-success” sera défini si champ password est valide.
La dernière étape consiste à désactiver le bouton tant que le formulaire n’est pas valide. Pour cela nous allons utiliser la directive “ng-disabled” :

Useful Link

Form JSON MySQL
http://www.phpcodify.com/how-to-post-data-using-angularjs/

Form JSON MySQL
http://tutlane.com/tutorial/angularjs/angularjs-http-post-method-http-post-with-parameters-example

PHP test, write a Fibonacci function

Write a function that computes the list of the first 100 Fibonacci numbers. By definition, the first two numbers in the Fibonacci sequence are 0 and 1, and each subsequent number is the sum of the previous two. As an example, here are the first 10 Fibonnaci numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, and 34.

function Fibonacci($limite){
	$Sequence1 = 0;
	$Sequence2 = 1;
	$array_finobacci = array();
	
	for($i=0; $i<$limite; $i++){
		$array_finobacci[$i] = $Sequence1;
		$sum = $Sequence1+$Sequence2;
		$Sequence1=$Sequence2;
		$Sequence2=$sum;
	}
	print_r(implode(',', $array_finobacci));
}
$limite = 10;
Fibonacci($limite);

PHP test, write a function to combine two strings

Write a function that combines two lists by alternatingly taking elements. For example: given the two lists [a, b, c] and [1, 2, 3], the function should return [a, 1, b, 2, c, 3].

$arr1 = array('a','b','c');
$arr2 = array(1,2,3);

function CombineTableau($arr1, $arr2){
	$arr3 = array();
	
	for($i=0; $i<(count($arr1)); $i++){
			$result = array_push($arr3, $arr1[$i]).''.array_push($arr3, $arr2[$i]);	
	}
	return $arr3;
}

CombineTableau($arr1, $arr2);

PHP test, use a for-loop, a while-loop, and recursive

Write three functions that compute the sum of the numbers in a given list using a for-loop, a while-loop, and recursion.

//for loop
function AdditionFor($list){
	$list_array = explode(',',$list);
	$rows_total = count(($list_array));
	$sum_array = array();
	
	for($i=0; $i<$rows_total; $i++)
	{
		$sum_push = array_push($sum_array, $list_array[$i]);
		$sum = array_sum($sum_array);
	}
	print_r('<p style="font-size: 20px; font-weight: bold;">'.$sum.'</p>');
}
$list = '1,4,16,37,120';
AdditionFor($list);

//while loop
function AdditionWhile($list){
	$list_array = explode(',',$list);
	$rows_total = count(($list_array));
	$sum_array = array();
	$i = 0;
	
	while($i < $rows_total){
		$sum_push = array_push($sum_array, $list_array[$i]);
		$sum = array_sum($sum_array);
		$i++;
	}
	print_r('<p style="font-size: 20px; font-weight: bold;">'.$sum.'</p>');
}
$list = '1,4,16,37,120'; 
AdditionWhile($list);

//recursive
$list = '1,4,16,37,120';

function AdditionRecursive($list){
	$list_array = explode(',',$list);
	$sum = array_sum($list_array);
	print_r('<p style="font-size: 20px; font-weight: bold;">'.$sum.'</p>');
}

AdditionRecursive($list);

PHP Remove a Single Character in a String in an Array in Several Keys

Creation of a function to remove a single character in a string from an array.

Example: remove_from_str("1,3,6,7,56,6,96", 6) must return array(1,3,7,56,96) 

function remove_from_str($str, $remove)
{
	$tmp = explode(',',$str);
	$result = array_diff($tmp,[$remove]);
	return $result;
}

var_dump(remove_from_str('1,3,6,7,56,6,96', 6)); //Display array(5) { [0]=> string(1) "1" [1]=> string(1) "3" [3]=> string(1) "7" [4]=> string(2) "56" [6]=> string(2) "96" }

PHP Capitalize Every Odd Character from Left to Right

Code to capitalize every odd character of a string from left to right:

$string = "abcdefghijkl";

for ($i = 0; $i < strlen($string); $i++)
{
	if ($i % 2== 0)
	{
		$s = substr($string, 0, $i) . strtoupper($string[$i]) . substr($string, $i+1, strlen($string));
		$string =$s;
	}
}

echo $string; //display AbCdEfGhIjKl

Useful Links

http://www.mustbebuilt.co.uk/php/select-statements-with-pdo/

PHP PDO to extract multiple rows

PDO to create an array which is looped to extract the data


//MySQL query 
$stmt = $connexion->query('SELECT * FROM cocktail');

//Loop
foreach($stmt as $row)
{
	//Display
	echo '<li>'.$row['nom_cocktail'].' '.$row['categorie_cocktail'].'</li>';
}

PHP PDO using an associate array

Code to extract one record using an associative array, with PHP PDO MySQL.


//MySQL query 
$stmt = $connexion->query('SELECT * FROM cocktail');

//Associative array
$row = $stmt->fetch(PDO::FETCH_ASSOC);

//Display
echo $row['nom_cocktail'];
echo '<br/>';
echo $row['categorie_cocktail'];

Activate jQuery ui in WordPress

If you use Worpdress and that you whish to use jQuery ui, you must to active jQuery ui on your WordPress.
Check this link : https://developer.wordpress.org/reference/functions/wp_enqueue_script/

jQuery and jQuery-ui are already registered with WordPress. You need enqueue them to load them on the page. But you are using ‘wp_register_script()’ instead of ‘wp_enqueue_script()’ within your ‘my_scripts_method()’ function.

function my_scripts_method() 
{
  wp_enqueue_script('jquery');
  wp_enqueue_script('jquery-ui-core');
  wp_enqueue_script('jquery-ui-tabs');
}
add_action('wp_enqueue_scripts', 'my_scripts_method'); 

Note: you may want to load them conditionally by using ‘wp_script_is()’. Example:

if( !wp_script_is('jquery-ui-tabs') ) 
{     
  wp_enqueue_script('jquery-ui-tabs');
}