Friday, November 23, 2012

Collection : PHP : Insert Data Function

In my previous post we added select_tag function for views as a helper function. Now we will add some function for inserting record. The names of functions might be similar to rails methods. This becomes easy for me to keep it simple to remember.

Lets consider we have some products table with id, name and description columns. As I have kept id auto generated we will not add if field in form.

In new.php
  1. <form id="product" method="POST" action="create.php" >
  2.  <input name="product[name]" type="text" value="" />
  3.  <textarea rows="6" name="product[description]"> </textarea>
  4.  <input id="product_submit" type="button" value="Save" onclick="submit();" />
  5. </form>
Check View.

Now when you click on save button it should redirect you to create.php. For now just add
  1. <?php print_r($_POST); ?>

and you can see (in view) Check View.

If you need to validate the records you can just add some code before the function we are going to add.
But I will just keep it simple, so directly going to add it to the database.

In create.php
  1. require_once 'includes/php/active_queries.php';
  2. insert_record($_POST['product'], "products");
  3. header('Location: index.php');

I have added active_queries.php, with this we will insert the data in table.
  1. /**
  2.  * For Inserting a single record
  3.  * @param array $record <p>Array of single record</p>
  4.  * @param string $model <p>Table name in which you want to make changes</p>
  5.  */
  6. function insert_record($record, $model) {
  7.   $fields = count($record);
  8.   if ($fields > 0) {
  9.     $i = 0;
  10.     $k = 0;
  11.     $insert = "INSERT INTO " . $model . " (";
  12.     foreach ($record as $key => $value) {
  13.       $k++;
  14.       $insert .= $key;
  15.       if ($fields > $k) {
  16.         $insert .= ", ";
  17.       }
  18.     }
  19.     $insert .= ") VALUES (";
  20.     foreach ($record as $key => $value) {
  21.       $i++;
  22.       if (gettype($value) == 'string') {
  23.         $insert .= " '" . pg_escape_string($value) . "'";
  24.       } else {
  25.         $insert .= $value;
  26.       }
  27.       if ($fields > $i) {
  28.         $insert .= ", ";
  29.       }
  30.     }
  31.     $insert .= ")";
  32.     $result = pg_query($insert);
  33.     return pg_affected_rows($result);
  34.   }
  35. }

This function will run loop of array twice. First to get the keys and then the values. And then it will add the data to the database. Once the query runs successfully it will return to the index page as we have mentioned header location as index.php. And you can see the inserted records.
Check Form View and Check Index View.

Now what if we want to add multiple records in one form/ click. This is not required for now but this can be used in nested_attributes.

So I added multiple_products.php in which we will add multiple fields.
  1. <form id="products" method="POST" action="create.php" >
  2.   <input name="multiple" type="hidden" value="true" /><br />
  3.   <?php for ($i=1; $i<=3; $i++) { ?>
  4.     <i><?php echo $i ?>. Name :</i><br />
  5.     <input name="products[<?php echo $i ?>][name]" type="text" value="" />    
  6.     <i>Description :</i><br />
  7.     <textarea rows="6" name="products[<?php echo $i ?>][description]"> </textarea><br />
  8.   <?php } ?>
  9.   <input id="product_submit" type="button" value="Save" onclick="submit();" />
  10. </form>
Check View

We are not creating another php file to submit these products to database. We will use the same create.php for which I added hidden field as multiple=true

In active_queries.php
  1. /**
  2.  * For Inserting multiple records
  3.  * @param array $records <p>Array of records</p>
  4.  * @param string $model <p>Table name in which you want to make changes</p>
  5.  */
  6. function insert_multiple_records($records, $model) {
  7.   foreach ($records as $record) {
  8.     insert_record($record, $model);
  9.   }
  10. }

And in create.php need to change some code. Instead of
  1. insert_record($_POST['product'], "products");

change code to
  1. if(isset($_POST['multiple'])){
  2.   insert_multiple_records($_POST['products'], "products");
  3. }else{
  4.   insert_record($_POST['product'], "products");
  5. }
Check View.

This will just get all data in and will run in loop which will call previous function(insert_record()) for each record array.

So after redirecting to index page we can view the inserted to reqords . Check View.

You can download whole source from github

Monday, November 19, 2012

Collection : PHP : select_tag

Learning PHP is fun to me but really miss the available helpers in Rails.
For example form helpers like form/ select_tag/ text_field and others.

I dont know whether these are already available in php or not.
So I added one file as common_helper.php and that can be directly required or just added separate (module_name)_helper.php and require common_helper.php in the new file. I have added module wise view helpers, so that I can keep the common helper functions and module wise helper function separate from each other.

This function creates a HTML select with options and selected option. Parameters required are :
  1. $name as string (Name for select node).
  2. $options as array (Array for generating options).
  3. $selected as string or integer - optional - (Selected value or blank string).
  4. $css_class as string - optional - (Css class name(s)).
  5. $onchange as string - optional - (onchange functionality)
This will append the given name and class name to select tag. Selected value will be selected in options by comapering the $selected.
Options send to the helper function needs to be array.
For example:
1. array(1, 2, 3, 4, 5, 6, 7);
Or
2. array(array(0,"0 Hours"), array(1,"1 Hour"), array(2,"2 Hours"), array(3, "3 Hours"), array(4, "4 Hours"));
Still for making work this code you will need to pass first 2 mandatory parameters which are name and array of options which will create the option tags for select_tag.

  1. <?php 
  2.   /**
  3.   * Creates a HTML select with options and selected option.
  4.   * @param string $name <p>Name for select node</p>
  5.   * @param array $options <p>Array for generating options</p>
  6.   * @param string $selected <p>Selected value or blank string. Can be string or integer.</p>
  7.   * @param string $css_class <p>Css class name(s) as a string</p>
  8.   * <p>
  9.   * This will append the given name and class name to select tag.
  10.   * Selected value will be selected in options by comapering the $selected.
  11.   * Options send to the helper function needs to be array
  12.   * For example:
  13.   * 1. array(1, 2, 3, 4, 5, 6, 7);
  14.   * Or
  15.   * 2. array(array(0,"0 Hours"), array(1,"1 Hour"), array(2,"2 Hours"), array(3, "3 Hours"), array(4, "4 Hours"));
  16.   * </p>
  17.   */
  18.   function select_tag($name, $options, $selected="", $css_class="", $onchange=""){
  19.     $select_tag = '<select class="' . $css_class . '" name="'.$name;
  20.     if($onchange!=""){
  21.       $select_tag .= '" onchange="'.$onchange;
  22.     }
  23.     $select_tag .= '">';
  24.     $select_options = "";
  25.     foreach($options as $a) {
  26.       if(is_array($a)){
  27.         $ky = $a[0];
  28.         $val = $a[1];
  29.       }else{
  30.         $ky = $a;
  31.         $val = $a;
  32.       }
  33.       $select_options .= '<option value="' . $ky . '"';
  34.       if($selected==$ky){
  35.         $select_options .= ' selected="selected"';
  36.       }
  37.       $select_options .= '>' . $val . '</option>';
  38.     } 
  39.     $select_tag .= $select_options . '</select>';   
  40.     return $select_tag;
  41.   } 
  42. ?>

So now in view we can directly add in php tag

  1. <?php echo select_tag("select_name", array(), $selected_value, "classname", "onchange_javascript_function(this.value);"); ?>

In the project I am working on needed the onchange javascript function.
Its not mandatory. So you can just avoid or remove that from the code.

This code is available on github : php_common_helpers.git.

Friday, November 16, 2012

Collection : Javascript : Validating max length

There are some scripts/ functionalities which are commonly and mostly used in many web based applications. I would like to keep some in the collection with us. These might be simple for the readers but are very important to make a note of it.

In this post I will keep note of 1 javascript function which restricts the user by adding more than the specific limit for the input. Or validating the input for certain limit to enter.

In Javascript file
/* check_the_max_length(input, maxLen) 
  input  : need a id or class of input
  maxLen : IE do not accept maxlength so passing it as a parameter.
*/
function check_the_max_length(input, maxLen){
  var val = $(input).val();
  var left = maxLen - val.length;
  var remaining_points = left<=0 ? 0 : left
  $('#counter').html(remaining_points + '/' + maxLen);
  if (val.length >= maxLen) {
      $(input).val(val.slice(0, maxLen));
  }
}
Considering in view
<%= f.input :description, :as => :text, :input_html => {:style => "width:450px;"}
I added some javascript in views, as application's most of the views are on popups. In main view, where popups will get displayed, add following lines at bottom in script tag.
$('#description').live('keyup keydpress', function(e) {
  check_the_max_length('#description', 220);
});
As we read, for IE, maxlength was not working, there was another bug. while entering paragraphs it do no calculate properly. For example: if I enter 4 paras the count will show I still have 4 values to enter. But max length attribute actually do not let you enter the value. So removed the maxlength attribute from views for inputs and added slice method which will actually cut down the text to original required count. SO the above function is the solution for both bugs.

Monday, November 5, 2012

Postgres : Server Installation and settings

Postgres is one of the popular database server for Ruby on Rails Applications. This post takes us step by step, installation and some important settings.

Postgres 9.1.x installation steps
sudo add-apt-repository ppa:pitti/postgresql
sudo apt-get update
sudo apt-get install postgresql
This will install the postgresql to the server/ your local machine. If you just want to use it locally then these steps are enough. But if you also want to use this database available for other machines then you have to add the ip to pg_hba.conf for making availablity for that ip machine only.
There is also other option for making database available if your ip is not stable. which is as given below. But also suggested use this only if server is only for internal use. For this we need to make following changes in

/etc/postgresql/9.1/main/pg_hba.conf(find following and make changes as shown)
# TYPE  DATABASE     USER  ADDRESS        METHOD
  local all          all                  trust
  host  all          all   127.0.0.1/32   trust
And another to the same file
# IPv4 local connections:

# host  all          all   127.0.0.1/32   md5
  host  all          all   0.0.0.0/0      trust
other file to make changes is /etc/postgresql/9.1/main/postgresql.conf
port = 5432
listen_addresses = '*'
And then just restart the server.
sudo /etc/init.d/postgresql restart
Install pgAdmin3
sudo apt-add-repository ppa:flexiondotorg/postgres
sudo apt-get update
sudo apt-get install pgadmin3