PHP Functions: A Beginner’s Guide | PHP Beginner to Advance

Functions are an essential part of any programming language, and PHP is no exception. In this blog post, we’ll be taking a look at how to create and use functions in PHP, including built-in functions and user-defined functions.

Built-in Functions in PHP

PHP comes with a variety of built-in functions that can be used to perform common tasks, such as string manipulation, mathematical operations, and array manipulation. Some examples of built-in functions in PHP include:

  • strlen(): Returns the length of a string
  • round(): Rounds a number to a specified number of decimal places
  • count(): Counts the number of elements in an array

Here’s an example of how to use the built-in strlen() function to find the length of a string:

$name = "John Doe";
$length = strlen($name);
echo "The length of the string is: " . $length;

User-Defined Functions in PHP

In addition to built-in functions, you can also create your own functions in PHP. User-defined functions allow you to organize your code and reuse it throughout your program. Here’s an example of how to create a simple user-defined function that adds two numbers together:

function add($a, $b) {
  return $a + $b;
}

$result = add(3, 5);
echo "The result is: " . $result;

In this example, we’ve created a function called add() that takes in two parameters, $a and $b. Inside the function, we use the return statement to return the sum of $a and $b.

Functions in PHP can also accept an optional parameter with a default value, which can be used if no value is passed to the function. Here’s an example of how to create a user-defined function that calculates the area of a rectangle with a default value for width.

function rectangle_area($height, $width = 5) {
  return $height * $width;
}

$area = rectangle_area(10);
echo "The area is: " . $area;

In this example, width parameter has a default value of 5, if no width value is passed to the function, it will use the default value.

In Conclusion

Functions are an essential part of programming and are a great way to organize your code and make it more reusable. Whether you’re using built-in functions or creating your own, understanding how to use functions in PHP is an important part of becoming a proficient PHP developer.

Here are the parts of the series

The Basic Syntax of PHP: A Beginner’s Guide | PHP Beginner to Advance

PHP, or Hypertext Preprocessor, is a popular server-side programming language that is widely used for building dynamic websites and web applications. In this blog post, we’ll be taking a look at the basic syntax of PHP, including variables, data types, and control structures.

Variables in PHP

A variable in PHP is a container that holds a value. Variables are used to store data and can be used throughout your program. In PHP, variables are declared using the dollar sign ($), followed by the variable name. For example:

$name = "John Doe";

In this example, we’ve declared a variable called $name and assigned it the value “John Doe”.

Data Types in PHP

In PHP, there are several data types that can be used to store different types of data. The most common data types in PHP are:

  • String: A string is a sequence of characters. Strings are enclosed in double or single quotes. For example:
$name = "John Doe";
  • Integer: An integer is a whole number (positive or negative) without a decimal point. For example:
$age = 25;
  • Float: A float is a number with a decimal point. For example:
$price = 9.99;
  • Boolean: A boolean is a true or false value. For example:
$is_admin = true;
  • Array: An array is a collection of values that can be accessed using an index. For example:
$colors = ["red", "green", "blue"];
  • Object: An object is an instance of a class. Objects can have properties and methods. For example:
class User {
  public $name;
  public $age;
}
$user = new User;
$user->name = "John Doe";
$user->age = 25;

Control Structures in PHP

Control structures are used to control the flow of execution of your program. The most common control structures in PHP are:

  • if/else: The if/else statement is used to test a condition and execute a block of code if the condition is true. For example:
if ($age >= 18) {
  echo "You are an adult.";
} else {
  echo "You are a minor.";
}

for loop: The for loop is used to iterate over a block of code a specific number of times. For example:

for ($i = 0; $i < 10; $i++) {
  echo $i;
}
  • while loop: The while loop is used to iterate over a block of code while a condition is true. For example:
$i = 0;
while ($i < 10) {
  echo $i;
  $i++;
}
  • foreach loop: The foreach loop is used to iterate over arrays and objects. For example:
$colors = array("red", "green", "blue");
foreach ($colors as $color) {
  echo $color;
}

This will give you a basic idea of PHP programming.

Here are the parts of the series

Introduction to PHP: The Language of the web | PHP Beginner to Advance

After working with PHP for 14 years, I was thinking about how the new developers starting with PHP who has little to no knowledge of PHP. So I thought to write a series of blog posts that will help newcomers. So let’s dive in.

PHP, or Hypertext Preprocessor, is a popular server-side programming language that is widely used for building dynamic websites and web applications. The language was first created in 1995 by Rasmus Lerdorf and has since grown to become one of the most widely-used programming languages on the web.

PHP is an open-source language, meaning that it is free to use and distribute. It is also easy to learn, making it a popular choice for beginners and experienced developers alike. The language is particularly well-suited for web development, as it allows for the creation of dynamic pages that can interact with databases and other web services.

The basic syntax of PHP is similar to other languages such as C and Perl. It uses a combination of HTML, CSS, and JavaScript to create dynamic web pages. PHP code is executed on the server and the result is returned to the client as HTML, which is then displayed in the user’s web browser.

One of the benefits of using PHP is that it can be easily integrated with other technologies such as databases (e.g MySQL) and web frameworks (e.g Laravel, CodeIgniter, Symfony) to create powerful web applications.

To get started with PHP, you’ll need a web server (e.g Apache, Nginx) and a text editor to write your code. There are also a number of development environments available, such as XAMPP and WAMP, that provide an easy way to set up a local web server for testing and development.

Once you’ve set up your environment, you can start experimenting with PHP by creating simple scripts and experimenting with the language’s built-in functions and control structures. You can also refer to resources such as PHP documentation and online tutorials to learn more about the language.

Further Reading:

These are some of the books that can be helpful in learning PHP. Additionally, there are numerous tutorials, videos, and online courses available that can help you get started with PHP.

In conclusion, PHP is a powerful, flexible, and easy-to-learn programming language that is well-suited for web development. Whether you’re a beginner or an experienced developer, there are plenty of resources available to help you learn and master the language.

Here are the other parts of the series

  • Introduction to PHP: The Language of the web | PHP Beginner to Advance
  • More to Come…

Faceted Search (Layered Search) on MySQL database with example.

Last few day I was searching for the layered search using MySQL. Layered Search is actually a Faceted Search. (Magento, a highly professional e-commerce platform on php name it Layered Search). Faceted Search can be done using two way MySQL/Any DB Application or using Apache Solr.

In this post I will show you how we can do Faceted search using MySQL database. You need a specific database schema, but it’s feasible. Here’s a simple example:

product Table

+----+------------+
| id | name       |
+----+------------+
|  1 | blue paint |
|  2 | red paint  |
+----+------------+

classification Table

+----+----------+
| id | name     |
+----+----------+
|  1 | color    |
|  2 | material |
|  3 | dept     |
+----+----------+

product_classification Table

+------------+-------------------+-------+
| product_id | classification_id | value |
+------------+-------------------+-------+
|          1 |                 1 | blue  |
|          1 |                 2 | latex |
|          1 |                 3 | paint |
|          1 |                 3 | home  |
|          2 |                 1 | red   |
|          2 |                 2 | latex |
|          2 |                 3 | paint |
|          2 |                 3 | home  |
+------------+-------------------+-------+

So, say someones search for paint, you’d do something like:

SELECT p.* FROM product p WHERE name LIKE '%paint%';

This would return both entries from the product table.

Once your search has executed, you can fetch the associated facets (filters) of your result using a query like this one:

SELECT c.id, c.name, pc.value FROM product p
   LEFT JOIN product_classification pc ON pc.product_id = p.id
   LEFT JOIN classification c ON c.id = pc.classification_id
WHERE p.name LIKE '%paint%'
GROUP BY c.id, pc.value
ORDER BY c.id;

This’ll give you something like:

+------+----------+-------+
| id   | name     | value |
+------+----------+-------+
|    1 | color    | blue  |
|    1 | color    | red   |
|    2 | material | latex |
|    3 | dept     | home  |
|    3 | dept     | paint |
+------+----------+-------+

So, in your result set, you know that there are products whose color are blue and red, that the only material it’s made from is latex, and that it can be found in departments home and paint.

Once a user select a facet, just modify the original search query:

SELECT p.* FROM product p
   LEFT JOIN product_classification pc ON pc.product_id = p.id
WHERE 
   p.name LIKE '%paint%' AND (
      (pc.classification_id = 1 AND pc.value = 'blue') OR
      (pc.classification_id = 3 AND pc.value = 'home')
   )
GROUP BY p.id
HAVING COUNT(p.id) = 2;

So, here the user is searching for keyword paint, and includes two facets: facet blue for color, andhome for department. This’ll give you:

+----+------------+
| id | name       |
+----+------------+
|  1 | blue paint |
+----+------------+

So, in conclusion. Although it’s available out-of-the-box in Solr, it’s possible to implement it in SQL fairly easily.

 

Thanks stackoverflow.com

Adding New Fields to the attachment of wordpress

Recently I was developing plugin for image features. I have to add some fields to the attachment window of wordpress or I can say in Add media box.

We can achieve this by using two hooks of wordpress.
“attachment_fields_to_edit” and “attachment_fields_to_save”;

attachment_fields_to_edit

function get_attachment_fields_to_edit($post,$errors=null){
 // Some Code
 $form_fields = apply_filters("attachment_fields_to_edit", $form_fields, $post);
 // Some Code
 }
  • $form_fields is a special array which will be described in detail in a moment.
  • $post is the attachment as an object (attachments are treated as post objects in WordPress).

attachment_fields_to_save

functionmedia_upload_form_handler(){
	//Some Code
	$post=apply_filters("attachment_fields_to_save",$post,$attachment);
	//Some Code
}
  • $post is the attachment as an array (attachments are treated as post objects in WordPress).
  • $attachment is the attachment part of the form $_POST which will include the fields setup through the attachment_fields_to_edit hook.

Note: Be careful in your code, as $post is sent to one function as an object and to the other as an array.

We will add this fields information to Custom Fields.

How to add this Fields to Custom Fields for Working is Properly

The new fields being added will be saved as post meta, just like the custom fields section of the post/page edit screen. Fields prefixed with an underscore (_my_custom_field) will not be listed in the drop down of available custom fields on the post/page screen; all other existing post meta fields will be listed. We can use this knowledge to hide the fields we’re adding to the media form, since they aren’t relevant for posts/pages.

There is a similar rule to keep in mind when choosing the $form_fields array key to use for your new field. Here, if you use an underscore ($form_fields[‘_my_custom_field’]) your field will be skipped and will not be added to the form.

So in order to show our fields in the media form, but also not list them in the page/post custom fields drop down, we must combine both methods. This will invlove both the edit and save functions we’ll be creating. For the ‘attachment_fields_to_edit‘ hook we’ll set the $form_fields keys up to not have underscore prefixes, and for the ‘attachment_fields_to_save‘ hook we’ll prefix our fields with an underscore before saving them as post meta. This is a workaround worth doing in order to not muddy our users’ interface with unneeded info.

Hook 1: attachment_fields_to_edit

<?php
/**
 * Adding our custom fields to the $form_fields array
 *
 * @param array $form_fields
 * @param object $post
 * @return array
 */
function my_image_attachment_fields_to_edit($form_fields, $post) {
	// $form_fields is a special array of fields to include in the attachment form
	// $post is the attachment record in the database
	// $post->post_type == 'attachment'
	// (attachments are treated as posts in WordPress)
	// add our custom field to the $form_fields array
	// input type="text" name/id="attachments[$attachment->ID][custom1]"
	$form_fields["custom1"] = array(
	"label" => __("Custom Text Field"),
	"input" => "text", // this is default if "input" is omitted
	"value" => get_post_meta($post->ID, "_custom1", true)
	);
	// if you will be adding error messages for your field,
	// then in order to not overwrite them, as they are pre-attached
	// to this array, you would need to set the field up like this:
	$form_fields["custom1"]["label"] = __("Custom Text Field");
	$form_fields["custom1"]["input"] = "text";
	$form_fields["custom1"]["value"] = get_post_meta($post->ID, "_custom1", true);
	return $form_fields;
}
// attach our function to the correct hook
add_filter("attachment_fields_to_edit", "my_image_attachment_fields_to_edit", null, 2);

The $form_fields array has several options for including different types of inputs and custom content. I’ve compiled the various methods below with notes and screenshots of how they render in the form.

Text Input

// input type="text"
$form_fields["custom1"]["label"] = __("Custom Text Field");
$form_fields["custom1"]["input"] = "text"; // this is default if "input" is omitted
$form_fields["custom1"]["value"] = get_post_meta($post->ID, "_custom1", true);

Hook 2: attachment_fields_to_save

Saving your custom fields is a much simpler process than adding them to the form; just check if your field is set and update its value as post meta. Remeber to prefix your field with an underscore when saving to hide it on the post/page edit screen.

/**
 * @param array $post
 * @param array $attachment
 * @return array
 */
function my_image_attachment_fields_to_save($post, $attachment) {
 // $attachment part of the form $_POST ($_POST[attachments][postID])
 // $post attachments wp post array - will be saved after returned
 // $post['post_type'] == 'attachment'
 if( isset($attachment['my_field']) ){
 // update_post_meta(postID, meta_key, meta_value);
 update_post_meta($post['ID'], '_my_field', $attachment['my_field']);
 }
 return $post;
}

You can also add errors here that will automatically be displayed below your field in the form. The$post['errors'] array gets merged with the $form_fields array before being sent through theattachment_fields_to_edit hook.

/**
 * @param array $post
 * @param array $attachment
 * @return array
 */
function my_image_attachment_fields_to_save($post, $attachment) {
 if( isset($attachment['my_field']) ){
 if( trim($attachment['my_field']) == '' ){
 // adding our custom error
 $post['errors']['my_field']['errors'][] = __('Error text here.');
 }else{
 update_post_meta($post['ID'], 'my_field', $attachment['my_field']);
 }
 }
 return $post;
}

Thanks to http://net.tutsplus.com

I have posted here for my future reference.