Various Issues, Tips and Methods

These tips are for those who have experience in PHP platform of at least 2-3 months. These tips will help you directly dive into some of the things that mostly overlook at learning time and latter create problems in writing good code and building confidence.

Create/maintain blocks of code
Use less number of tables
Height and Width in img tags
Initialize all variables
Comments in HTML and PHP
Check/Validate HTML
Separate files for CSS and Javascript also
Know your editor
Know your surrounding
Submitting an array to PHP from HTML
CSS: Table less design
Simple Design using table
Get X and Y coordinate of an element in a HTML document
Read sql data from a large file/csv file at very high speed
Encode data before saving data in table
Converting string to array and array to string in PHP: explode and implode
Dynamic Variables in PHP (Variable varaible)

Create/maintain blocks of code

Try to create block of code that looks separate in PHP and HTML
if you see there is lots of PHP codes and little HTML then it will be better to use echo for HTML there.

If you see little PHP and lots of HTML then it will be better to come out of PHP block.
Some do something like this.

-- real PHP code --
echo '<b>Hello</b>';
echo '<b>Hello</b>';
echo '<b>Hello</b>';
---
---
echo '<b>Hello</b>';
echo '<b>Hello</b>';
-- real PHP code --

?>
It is bad using this way. Why?
It is difficult to design and change HTML when required. It will unnecessary create trouble managing double quotes and single quotes.
PHP parser will also have to check the codes.
When there is only or more of HTML then why PHP need to look into it!
So it is better in this case-

<b>Hello</b>
<b>Hello</b>
<b>Hello</b>
<b>Hello</b>
---
---
<b>Hello</b>
<b>Hello</b>

Now HTML is clear!.

Use less number of tables

If you are a HTML Programmer then always try to use less number of tables. Why?
Browser can only show your table content only when all the contents come to it.
In case you used a big table for whole page layout then even if contents related to upper parts comes, it cannot show your content to user.
Users have to wait for whole content to download and checked by browser. So, if you are not good at div and span etc. Then you can do one thing: part the table for header body and footer.
Table will take as much height as required by content.

<table id="header" width="100%" cellspacing="0" border="1" cellpadding="3" align="center">
<tbody>
  <tr>
    <td></td>
    <td></td>
    <td></td>
  </tr>
</tbody>
</table>
<table id="body" width="100%" cellspacing="0" border="1" cellpadding="3" align="center">
<tbody>
<tr>
  <td></td>
  <td></td>
  <td></td>
</tr>
</tbody>
</table>
<table id="footer" width="100%" cellspacing="0" border="1" cellpadding="3" align="center">
<tbody>
<tr>
  <td></td>
  <td></td>
  <td></td>
</tr>
</tbody>
</table>

So if you are thinking why I provided 3 cols for table then here is a reason:
Generally body is divided into three parts. left side pane, middle body part (actual contents) and right side pane.
In left or right side there are links to other pages of your site. One side can be reserved for ad.
In header part you may or may not need three cols. For one col. you can write in first col. and delete others two cols. If you need only two then use so. This way you can
manage according to your need. It will be good to keep little margin for change. So I am using 3 cols.
You can do this for footer also.
Using 3 cols for each will make it easy for synchronizing among header, footer and body part in future.

Height and Width in img tags

Always use height and width with img tag (<img src="http://www2.blogger.com/path" height="" width="" />).
Why?
It makes you page loads faster in browser. Browser knows how much spaces they need to keep for images. They can show the text to user while images is still coming.

You should use alt attribute in img tags. Search engine cannot check image but can check alt tags. Alt tags are a small description of image.

Comments in HTML and PHP

Though comments take negligible time in PHP, in HTML it takes bandwidth in HTML.
So for long comments, use php comments. It is better for two reasons: First of all it hides your useful comments to those who do not need it and it saves bandwidth of your network. Because HTML comment will not show to user but still it will travel in network.

If you are a HTML programmer then you can use small HTML comments for marking table start-end etc.

Writing comments is very important.

Initialize all variables

Never left any variable un-initialized. Why?
It is a loophole for hacker.
It can generate programming mistakes, which you are not aware of if you new in script writing.
Now, how to detect all such variables?
Generally error reporting is not set to all in setting. It is good for live site.
For developmental platform, it is not good.
It will show you all the un-initialized variables.
It would be good if you do this in a common file used in all files.
So, this can easily be disabled in case you forgot after completing scripts.

<a href="http://php.net/error_reporting"><strong>error_reporting</strong></a>(E_ALL);
or
<a href="http://php.net/ini_set">ini_set</a>('display_errors',1);

Check/Validate HTML

Never left HTML tags open.
Like this:

<td><p> text...<td>

Here you will not see anything wrong in visual when <p> tags is open.
Check for these minor things when writing HTML. These may not affect your visual look but it will surely affect rendering speed in your browser. These all look small things but these small things affect a lot. Generally in the above case cellspacing will do your job instead of using <p>.
You can use HTML validator for checking your HTML.

Separate files for CSS and Javascript also

CSS and Javascript: in a separate file-
Generally people who write CSS write in separate file but some do not realize its true uses.
So they left it in the same HTML file. It is not only useful for HTML but also useful for caching for browser.
If you use a css file for css then it will be cached by your browser and for all the pages except first, it will use css file from cache instead of downloading
it every time. The same is applied for javascript file.

Know your editor

You should know you editor well. Generally people know some of the commands only. They know Ctrl+V, Ctrl+C, Ctrl+X, Ctrl+Z but don't know others which is equally important. Like Ctrl+B, which is for bookmark in Quanta. You can bookmark line/lines and go to bookmark directly using Alt+Page Up/Alt+Page Down. This will enhance your page viewing and saves lots of energy and time of your fingers and eye. So explore your editor.
For PHP Platform, I will support Quanta (Linux), Editplus and Eclipse.

Know your surrounding

If you program in PHP, don't think you should only know PHP. Knowing HTML, CSS, Javascript will help a lot. You should also give little consideration on MySQL and Apache configuration.

Submitting an array to PHP from HTML

Suppose you have 5 items to select. You provided checkboxes for these.
How you will get all the selected values in PHP.
For this you may use checkbox.
Here only important thing is checkbox name. Give name as chName[].
Here focus on last ([]).
Example:

HTML:
<input name="chItem[]" value="item1" type="checkbox">
<input name="chItem[]" value="item2" type="checkbox">
<input name="chItem[]" value="item3" type="checkbox">
<input name="chItem[]" value="item4" type="checkbox">
<input name="chItem[]" value="item5" type="checkbox">
PHP:
$items = $_POST['chItem']; // access yours items like this.
echo "Selected Items:";
foreach ($items as $val) {
echo "$val";
}

CSS: Table less design

Try with the bolow codes if you are looking for tableless design. Sometimes div with class 'floatLeft' will not be on proper places then Use spacer div whenever you face problem with div placement.

<style>
div.container {}
div.floatLeft {margin-right:20pt; float:left; }
div.spacer {clear:both}
</style>
<div class="container">
<div class="spacer"></div>
<div class="floatLeft">
aaa
</div>
<div class="floatLeft">
bbb
</div>
<div class="spacer"></div>
</div>

Div with float will only takes as much space as required by their content.

Simple Design using table

<style>
table caption{background-color:#cccc99;font-weight:bolder}
tr.r2 {background-color:#ffffff}
tr.r2 {background-color:#EEEFB3}
</style>

Check by using frame equal to none/above/below/hsides/lhs/rhs/vsides/box/border and rules equal to none/groups/rows/cols/all.

<table width="50%" align="center" cellpadding="3" cellspacing="0" border="1" frame="below" rules="rows">
<caption>Simple Design using table</caption>
<tr class="r1">
<td>aaaaaaaaaaa</td>
<td>aaaaaaaaaaa</td>
</tr>
<tr class="r2">
<td>bbbbbbbbbbb</td>
<td>bbbbbbbbbbb</td>
</tr>
<tr class="r1">
<td>ccccccccccc</td>
<td>ccccccccccc</td>
</tr>
<tr class="r2">
<td>ddddddddddd</td>
<td>ddddddddddd</td>
</tr>
</table>

Get X and Y coordinate of an element in a HTML document

<script>
// Get x coordinate of an element
function getX() {
var oElement = document.getElementById('myResponse');
var iReturnValue = 0;
while( oElement != null ) {
  iReturnValue += oElement.offsetLeft;
  oElement = oElement.offsetParent;
}
alert(iReturnValue);
}
// Get y coordinate of an element
function getY() {
var oElement = document.getElementById('myResponse');
var iReturnValue = 0;
while( oElement != null ) {
  iReturnValue += oElement.offsetTop;
  oElement = oElement.offsetParent;
}
alert(iReturnValue);
}
</script>
In Body tag of HTML:
<textarea id="myResponse" cols="100" rows="10"></textarea>

Read sql data from a large file/csv file at very high speed

I posted the logic for this here: Click here
Using this I am reading and inserting more than 8000 records in 4 seconds.

Encode data before saving data in table

Case: I got a record in database which is showing junk character on web page when retrieved from table. I tried different header for charset.
It was also saving in file also. There it were also creating problem.
Character was simple. That was (') only.
The difference exists due to window and Linux. In window it was not same.
So it is said, 'Encode data before storing data in database'.

When I encoded the data and then decoded the data from database, then it was showing properly.
Otherwise for showing purpose only, you can use header ("Content-Type:text/html; charset=iso-8859-1");
But it was not working want I tried to save the output from mysql to file. And I was opening that file in a text editor.

In the below example I have commented the header line, because I am now saving the data correctly in database.

htmlentities($value, ENT_QUOTES); // save to DB after encoding

html_entity_decode($r['info'], ENT_QUOTES); // get from DB and show this using decoding.

?>
You can also preserve your data using base64_encode() and base64_decode().
Data will be 33% larger than original data. This is especially suggested for binary data.

Converting string to array and array to string in PHP: explode and implode

string implode(string $glue, array $pieces) //Join array elements with a string
array explode(string $delimiter, string $string [, int $limit]) //Split a string by string

Suppose you are given list of items in excel sheet like this
item1
item2
item3
item4
....
...

Above text in text editor that will also come like that.
So considering it a long list, you have to labor hard getting the elements in this way:

item1,item2,....
So, here you can use this script:
$str1 = 'item1
item2
item3
item4
....
....';
$arr1 = explode ("n", $str1); // Items are separated by new line chars.
Now all items are in array. You can use this array anywhere. Example: in dropdown list/menu( select>).
or you can store the list in database like this:
$str2 = implode (',', $arr1);
It will produce output like this: item1, item2,...
Again for getting in array, you will use:
$arr1 = explode (",", $str1); // Items are separated by ',' chars.

Converting string to array and array to string in JavaScript: split and join

      str = 'zend';
      // JavaScript String to Array
t =  str.split(''); // no seperator means each char.
alert(t);
      // JavaScript Array to String
alert(t.join()) // you can provide glue like: join(':');
// array can be created like this way.
t2 = new Array('b', 'c', 'd');
alert(t2);

Creating Dynamic Variables in PHP

<?php
for($i=1; $i<=5; $i++) {
    ${'day'.$i} = true;
}
?>

Variables created will be $day1, $day2, $day3, $day4, $day5

  • # 1 - by Anonymous

    “Read sql data from a large file/csv file at very high speed”

    There is a very handy type of insert in MySQL called LOAD DATA INFILE which does this task for you much faster than any php code.

    LOAD DATA LOCAL INFILE
    ‘/path/to/file.txt’
    INTO TABLE my_sql_table
    FIELDS TERMINATED BY ‘,’
    LINES STARTING BY ” TERMINATED BY ‘\n’

    Check out the mysql documentation on this feature: http://dev.mysql.com/doc/refman/5.0/en/load-data.html

  • # 2 - by Anonymous

    “Read sql data from a large file/csv file at very high speed”There is a very handy type of insert in MySQL called LOAD DATA INFILE which does this task for you much faster than any php code.LOAD DATA LOCAL INFILE ‘/path/to/file.txt’INTO TABLE my_sql_table FIELDS TERMINATED BY ‘,’LINES STARTING BY ” TERMINATED BY ‘n’Check out the mysql documentation on this feature: http://dev.mysql.com/doc/refman/5.0/en/load-data.html

  • # 3 - by Satya Prakash

    Right!
    But in my case I have to provide a web page for a developer user who will take download file from maxmind and enter here.

  • # 4 - by Satya Prakash

    Right!But in my case I have to provide a web page for a developer user who will take download file from maxmind and enter here.

Comments are open for an year period. Please, write here on Facebook page.