RSS

Category Archives: php

common errors and tips while coding in php

[php][tip] How to manage variable variable name?

While handling html form, sometimes one need to have dynamic field names and will do it with string concatenation with the respective variable but the issue was there while handling the form action.
Following is the code chunk which explains it well how to use variable variable names in php:

<h2>Enter Marks</h2>
<form name=”frm” id=”frm” method=”post” action=””>
<?php
$subject = array(“Eng”,”Urdu”,”Maths”);
for($i=0 ; $i<count($subject) ; $i++)
{
print “<p>”;
print “<label>”.$subject[$i].”</label>”;
$value = “”;
if(isset($_POST[‘subject_’.$subject[$i]]))
$value = $_POST[‘subject_’.$subject[$i]];
print “<input type=’text’ name=’subject_”.$subject[$i].”‘ id=’subject_”.$subject[$i].”‘ value=$value >”;
print “</p>”;
}
?>
<input type=”submit” />
</form>

<?php
$subject = array(“Eng”,”Urdu”,”Maths”);
if(count($_POST)>0)
{
print “<h2>Form Values</h2>”;
extract($_POST);
for($i=0 ; $i<count($subject) ; $i++)
{
print “<p>”;
print “<strong>”.$subject[$i].”:</strong>”;
print ${‘subject_’.$subject[$i]};
print “</p>”;
}
}
?>

Thus ${‘string’.$variable} is the right way to access variable variable name 🙂

 
Leave a comment

Posted by on June 29, 2012 in php

 

Tags: , , , ,

[php][tip] How to map date field across different tables when one is of date format and the other of unixtimestamp?

While merging record of multiple tables into a single table, I need to merge the date field as well and the issue with merging date field is that the field in which I have to merge it have unixtimestamp and the source filed have the date format yyyy-mm-dd hh:ii:ss.

After searching alot on any mysql function that can convert date format, found nothing. Rather find strtotime php function to meet the purpose. Thus tried a bit lengthy way to merge two tables by first merging all the required data except date field and merge the date field afterwards by using following update query.

$query = "SELECT * FROM `src_table` ;
$result = mysql_query($query);
$dts = array();
while($row = mysql_fetch_array($result))
{
   $id = $row[‘id’];
   $dts[$id] = strtotime($row['date']);
}
foreach($dts as $id => $date)
{
   $query = "UPDATE dest_table set date = '".$date."'".
   " WHERE id = '".$id."'";
   mysql_query($query);
}

That’s it 🙂

 
Leave a comment

Posted by on December 10, 2011 in php

 

Tags: , , , , , ,

[php][tutorial] directory sorting by file type and last modified date

Following code is there to list all the files within the specified directory by sorting files by file type and last modified date respectively:

<?php
function sort_by_filetype($src='.')
{
$dirFiles = array();
if ($handle = opendir($src)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$extn = explode('.',$file);
$type = $extn[count($extn)-1];
$dirFiles[$type.$file] = $file;
}
}
closedir($handle);
}
ksort($dirFiles);
return $dirFiles;
}
function sort_by_filemtime($src='.')
{
$dirFiles = array();
if ($handle = opendir($src)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$date = filemtime($file);
$dirFiles[$date.$file] = $file;
}
}
closedir($handle);
}
ksort($dirFiles);
return $dirFiles;
}
$src = '.';
echo "<br><strong>Sort By File Type</strong>";
$dirFiles = sort_by_filetype($src);
foreach($dirFiles as $file)
{
echo "<br>".$file;
}

echo "<br><strong>Sort By Time</strong>";
$dirFiles = sort_by_filemtime($src);
foreach($dirFiles as $file)
{
echo "<br>".$file;
}
?>

Thats it 🙂

 
Leave a comment

Posted by on November 18, 2011 in php

 

Tags: , , ,

[php][tutorial] Simplest Pagination in PHP

Here is simplest code for pagination in php. Comments are there to make code self explanatory.

<?php

$data = array('1'=>'1','2'=>'2','3'=>'3','4'=>'4',
'5'=>'5','6'=>'6','7'=>'7','8'=>'8','9'=>'9','10'=>'10',
'11'=>'11','12'=>'12','13'=>'13','14'=>'14','15'=>'15',
'16'=>'16','17'=>'17','18'=>'18','19'=>'19','20'=>'20',
'21'=>'21');

$num_data = count($data);
if(!empty($_GET["start"])){
$start = $_GET['start'];
}else{
$start  = 0;
}

$limit           = 5; // Records per page
$current      = $start + $limit;
$back          = $start - $limit;
$next          = $start + $limit;
//Previous Page
$nav = '';
if($back >=0) {
$nav .= "<a href='?start=$back'>&laquo; Previous</a>
&nbsp;&nbsp;";
}

// Show navigation links
$x    = 1;
for($i=0;$i < $num_data;$i=$i+$limit){
if($i != $current){
$nav .= "<a href='?start=$i'>$x</a> ";
}else {
$nav .= "<b>$x </b>"; // bold selected page
}
$x    = $x+1;
}
// Next Page
if($current < $num_data) {
$nav .= "<a href='?start=$next'>Next &raquo;</a>";
}

$listing = '';
for($i= ($start+1); $i<= ($start+$limit) ; $i++)
{
$listing .= $data[$i]."<br>";
}

echo "<div align=center>".$listing."Pages: ".$nav."</div>";

?>

Thats it 🙂

I think its the simplest code for pagination in php, if you think its not, then please provide yours 🙂

Note: For showing the current number of records, following code is there

if($start+$limit >$num_data)
$c = $num_data;
else
$c = ($start+$limit);

echo "Records: ".($start+1)."-".$c." of ".$num_data; 
//1-10 of 20 etc
 
Leave a comment

Posted by on November 3, 2011 in php

 

Tags: , , , , , , , ,

[php][html] For Beginners

People often question about the initializing task of php, following are the few tasks that help a person get started with coding in php:

Task 1: Required Installations

All you need is an editor and localhost.

Task 2: Static Welcome Message Display

Start your installed (WAMP, LAMP, XAMPP, WAMP) server (Note:If your skype is there online then you need to signout skype for starting your server because of port conflict). Open Notepad++ and create new file at wamp/www for WAMP and applications/MAMP/htdocs for MAMP.

Place the following code in the file:

<?php
echo "Hello World";
?>

OR

Hello World

In your browser goto http://localhost and you will find your file listed there, click on the file and you will see a welcome message “Hello World” there.

tags are there to enclose php code. Echo will print the content.

Task 3: Display Name Dynamically

Previously we have displayed a hardcoded message, now display your name dynamically. W3schools is there for beginners. Just explore the html section and code a basic form.

<form name=”form1″ id=”form1″ action=”" method=”POST">

Enter your name:<input type=”text” name=”uname” id=”uname” />

<input type=”submit” name=”submit” id=”submit”
value=”Save Name” />

</form>

<?php

if(isset($_POST['submit']))

echo $_POST['uname'];

?>

$_POST array have all the submitted data of the form.

Refresh the file in the browser and you will see a form, just enter your name and submit it and you will see “Your Name: your_name_here”. Just explore html section of  W3schools and play with the layout of your form.

Task 4: Save Data in Database

Now comes interesting part of learning any programming lanaguage i.e. database interaction.

In your browser goto http://localhost, click phpMyAdmin option there.

Lets `user` be the name of your database,` user_info` be the name of your table having fields `name` and `roll_number` (it is auto incremented).

  • Here is a tutorial for creating database in phpMyAdmin
  • Here is a tutorial for creating table in phpMyAdmin
<form name="form1" id="form1" action="" method="POST">

Enter your name:<input type="text" name="uname" id="uname" />

<input type="submit" name="submit" id="submit"
value="Save Name" />

</form>

<?php

$con = mysql_connect("localhost",'root','root');
//host, user,password

mysql_select_db("user",$con) or die (mysql_error);

if(isset($_POST['submit']))

{

$query = "INSERT INTO user_info (name)
VALUES ('".$_POST['name']."')";

mysql_query($query) or die (mysql_error);

}

?>

Goto your table at phpMyAdmin and refresh the table, you will see your name there.

For listing records, updating and much more functions explore W3Schools SQL section.

This tutorial is there to let you know how simple and easy going php is. Once you are done with these basic tasks you can try modifying the html and php code to learn more.

Have a nice time in the world of php 🙂

 
4 Comments

Posted by on October 26, 2011 in php

 

Tags: , , , , , ,

|| php || tip || physical path tracking

Including file from nested directory is simple and straight forward while being at root directory, but for including files in php in nested directories beginners claim that they have did everything perfectly right but the file didn’t get called.
Following are the few cases for nested file calls,
1) ./ within the same folder e.g. currently in folder1/file1.php and want to access folder1/file2.php
2) ../ with the depth of one level e.g. currently in folder1/folder1.1/file3.php and want to access folder1/file2.php
3) ../../ with the depth of two levels e.g. currently in folder2/folder2.4/folder2.4.5/file4.php and want to access folder2/file5.php
4) ../../../ with the depth of three levels e.g. currently in folder5/folder5.3/folder5.3.1/folder5.3.1.7/file6.php and want to access folder5/file7.php

Thats it 🙂

 
Leave a comment

Posted by on October 19, 2011 in php

 

Tags: , , , ,

|| php || helping code || how to get base url in custom php?

Sometimes while coding in php, relative paths doesn’t work properly where they suppose to be, so for such cases one need an absolute url and for that need to concatenate the base url with the relative url as per requirement. Following code is there to get the base url.

$file_name = explode('/',$_SERVER['REQUEST_URI']);
$root_dir = "";
for($i = 0 ; $i< (count($file_name)-1) ;$i++) 
// -1 to exclude filename
{
$root_dir .='/'.$file_name[$i];
}

$base_url = 'http://'.$_SERVER['HTTP_HOST'].$root_dir;

$_SERVER array has many other useful info, just do print_r($_SERVER); and you can trace the SCRIPT_FILENAME of the current file,QUERY_STRING , SCRIPT_NAME, REQUEST_METHOD etc.

 
Leave a comment

Posted by on October 19, 2011 in php

 

Tags: , , ,

 
%d bloggers like this: