Tuesday, May 17, 2011

multidimensional array sorting in php

Note:- In this post I am sorting multidimensional array by first name if you want to sort by other field then remove first_name and write other field in
array_sort_by_column($people, 'first_name');
Note :- Remove "\" from all places I have added "\" because blogger posting not supported html tags and php opening tag

<\?php

$people = array(
    1 => array(
        'id' => 1,
        'first_name' => 'Kamran',
        'surname' => 'Ahmad',
        'age' => 25,
        'sex' => 'm'
    ),
    2 => array(
        'id' => 2,
        'first_name' => 'Adam',
        'surname' => 'Smith',
        'age' => 18,
        'sex' => 'm'
    ),
    3 => array(
        'id' => 3,
        'first_name' => 'Joe',
        'surname' => 'Bloggs',
        'age' => 23,
        'sex' => 'm'
    ),
    4 => array(
        'id' => 4,
        'first_name' => 'Amy',
        'surname' => 'Jones',
        'age' => 21,
        'sex' => 'f'
    )
);

function array_sort_by_column(&$arr, $col, $dir = SORT_ASC) {
    $sort_col = array();
    foreach ($arr as $key=> $row) {
        $sort_col[$key] = $row[$col];
    }

    array_multisort($sort_col, $dir, $arr);
}

array_sort_by_column($people, 'first_name');
?>
<\table width="500px" cellpadding="0" cellspacing="0" border="1">
    <\tr>
        <\td height="30px" align="center"><\b>ID<\/td>
        <\td height="30px" align="center"><\b>First name<\/b><\/td>
        <\td height="30px" align="center"><\b>Surname<\/b><\/td>
        <\td height="30px" align="center"><\b>Age<\/b><\/td>
        <\td height="30px" align="center"><\b>Sex<\/b><\/td>
  
foreach($people as $peo)
{
    echo "<\tr>";
    echo "<\td height='30px' align='center'>".$peo['id']."<\/td>";
    echo "<\td height='30px' align='center'>".$peo['first_name']."<\/td>";
    echo "<\td height='30px' align='center'>".$peo['surname']."<\/td>";
    echo "<\td height='30px' align='center'>".$peo['age']."<\/td>";
    echo "<\td height='30px' align='center'>".$peo['sex']."<\/td>";
    echo "<\/tr>";
}

?>

<\/table>

Thursday, May 5, 2011

export data from mysql database table in csv file using php

In this post we export data from mysql database table in csv file formate using php.

Note : Save bellow file as name  csvfile.php

<\?php
$host = 'localhost'; // MySql DataBase Host Name
$db = 'databasename'; // MySql DataBase Name
$user = 'root'; // MySql DataBase UserName
$pass = ''; // MySql DataBase Password

// Connect to the database
$link = mysql_connect($host, $user, $pass);
mysql_select_db($db);

require 'exportcsv.php';
$table="TableName"; // Table Name that you want to export in csv file from mysql database.

exportMysqlToCsv($table);
?>



Note: Save bellow file as name  exportcsv.php



<\?php
function exportMysqlToCsv($table, $filename = 'csvfilename.csv')
{
    $csv_terminated = "\n";
    $csv_separator = ",";
    $csv_enclosed = '"';
    $csv_escaped = "\\";

    $sql_query = "select * from $table";
    $result = mysql_query($sql_query);
    $fields_cnt = mysql_num_fields($result);
  
    $schema_insert = '';
    for ($i = 0; $i < $fields_cnt; $i++)
    {
        $l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed,
            stripslashes(mysql_field_name($result, $i))) . $csv_enclosed;
        $schema_insert .= $l;
        $schema_insert .= $csv_separator;
    } // end for
    $out = trim(substr($schema_insert, 0, -1));
    $out .= $csv_terminated;
    // Format the data
    while ($row = mysql_fetch_array($result))
    {
        $schema_insert = '';
        for ($j = 0; $j < $fields_cnt; $j++)
        {
            if ($row[$j] == '0' || $row[$j] != '')
            {
                if ($csv_enclosed == '')
                {
                    $schema_insert .= $row[$j];
                }
                else
                {
                    $schema_insert .= $csv_enclosed .
                    str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed;
                }
            }
            else
            {
                $schema_insert .= '';
            }
            if ($j < $fields_cnt - 1)
            {
                $schema_insert .= $csv_separator;
            }
        } // end for
        $out .= $schema_insert;
        $out .= $csv_terminated;
    } // end while
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Content-Length: " . strlen($out));
    // Output to browser with appropriate mime type, you choose ;)
    header("Content-type: text/x-csv");
    //header("Content-type: text/csv");
    //header("Content-type: application/csv");
    header("Content-Disposition: attachment; filename=$filename");
    echo $out;
    exit;
}
?>

Friday, March 25, 2011

url rewriting using .htaccess

URL Rewriting using .htaccess

Here is some example of URL Rewriting. If you are searching for URL Rewriting the bellow code help you for rewriting. In this post we are rewrite URL though .htaccess file. Bellow is some example for URL Rewriting using .htaccess file.

1) Redirecting non www URL to www URL

If we type on browser’s address bar domainname.com it will be redirected to www.domainname.com.

RewriteEngine On
RewriteCond %{HTTP_HOST} ^domainname\.com$
RewriteRule (.*) http://www.domainname.com/$1 [R=301,L]

2) Rewriting filename.php?id=111 to filename-111.html
Example : profile.php?id=111 to profile-111.html

It’s simple redirection rule in which php extension is hidden from browser address bar and generate dynamic url converted into a static URL.

RewriteEngine on
RewriteRule ^profile-([0-9]+)\.html$ profile.php?id=$1
Note: containing “?” character

3) Rewriting filename.php?id=111 to filename/name/111.html
Example: profile.php?id=111 to profile/kamran/111.html

In the following URL rewriting technique you can display the name of the profile in URL.

RewriteEngine on
RewriteRule ^profile/([a-zA-Z0-9_-]+)/([0-9]+)\.html$ profile.php?id=$2

4) Rewriting http://www.domainname.com/profile.php?username=abc to http://www.domainname.com/abc
Have you seen twitter.com or facebook.com. If you type http://twitter.com/ekamraan or http://facebook.com/ekamran in browser you can see my profile over there. If you want to do same kind of redirection i.e http://domainname.com/profile.php?username=abc to http://domainname.com/xyz then you need to add the following code to the .htaccess file.
RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ profile.php?username=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ profile.php?username=$1

5) Redirecting the domainname to a new subfolder of inside www or public_html.

If you have redeveloped your site and all the new development of site in "newfolder” of inside root folder. Then the new development of the site can be access like “http://www.domainname.com/newfolder”. Moving these files to the root newfolder can be a engaged process so you can use bellow code inside the .htaccess file and upload it under the root folder of the site. www.domainname.com point out to the files inside “newfolder”.

RewriteEngine On
RewriteCond %{HTTP_HOST} ^domainname\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.domainname\.com$
RewriteCond %{REQUEST_URI} !^/newfolder/
RewriteRule (.*) /newfolder/$1

Thursday, October 21, 2010

how to create static html page from a database table using php

In this post we are creating a html file or pages which is static page in specific loacation of folder from a databse table using php. In this program we are also creating folders in specific location maintain url.
This table contains all the data for the "static" pages of the site.

Note: Please remove all "\" from bellow code, I have use it because blogger does not show html tags.

Step 1. Create a table as bellow.

CREATE TABLE `template` (
  `id` bigint(200) NOT NULL auto_increment,
  `name` varchar(200) NOT NULL,
  `address` text NOT NULL,
  `city` varchar(200) NOT NULL,
  `country` varchar(200) NOT NULL,
  `companyname` varchar(200) NOT NULL,
  `empid` varchar(200) NOT NULL,
  PRIMARY KEY  (`id`)
);

Step 2. Copy bellow code and create a php file name refresh.html.

<\?php
ob_start();

/**************** DataBase Conectivity ************/
$connect = mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("test");

/************** Create Directory(Folder)*************/
$query_dir = "select * from template";
$ressel_dir = mysql_query($query_dir);
while($data_dir = mysql_fetch_array($ressel_dir))
{
            $datadir = $data_dir['name'];
            $datapage = $data_dir['id'];
           
            /**************Include Pages**************/
            include ("template.php");
            $content = ob_get_contents();
            ob_end_clean();

            $dir_name = strtolower(str_replace(' ', '-', $datadir));
            $dir_page = strtolower(str_replace(' ', '-', $datapage));

            @mkdir($dir_name, 0777, true);

            /*************** Create File Path *****************/
            $filename = $dir_name."/".$dir_page.".html";

            /************** Write contents on file ****************/
            $fp = fopen($filename, "w") or die("Could't open $filename");

            fwrite($fp, $content);
            fclose($fp);
}

echo "All File written Success Full<\br />";
echo "Congratulation HTML File has been created";

?>

Step 3. Copy bellow code and create a php file name template.php

$query= "select * from template where id='".$datapage."'";
$res = mysql_query($query) or die(mysql_error());
$data = mysql_fetch_assoc($res);
?>
<\html>
<\head>
            <\title>creating static html page from a database table using php<\/title>
<\/head>
<\body>
<\table border="0" cellpadding="0" cellspacing="0" width="100%">
            <\tr>
                        <\td><\b>Name<\/b><\/td>
                        <\td><\b>Address<\/b><\/td>
                        <\td><\b>City<\/b><\/td>
                        <\td><\b>Country<\/b><\/td>
                        <\td><\b>Company Name<\/b><\/td>
                        <\td><\b>Employee ID<\/b><\/td>
            <\/tr>
            <\tr>
                        <\td><\?=$data['name']?><\/td>
                        <\td><\?=$data['address']?><\/td>
                        <\td><\?=$data['city']?><\/td>
                        <\td><\?=$data['country']?><\/td>
                        <\td><\?=$data['companyname']?><\/td>
                        <\td><\?=$data['empid']?><\/td>
            <\/tr>
<\/table>
<\/body>
<\/html>

Monday, August 23, 2010

how to select limited characters from a table column in mysql

In MySQL you can draw on the LEFT() thread function to choose a fix digit of qualities as of the left of a specific data column which permits me to obtain an appearance at the primary little utterances in comment to estimate. In this situation I am fetching 100 characters.

<\?php
      $query = "select id, left(content, 100), title from tablename";
      $res = mysql_query($query);
      while($data = mysql_fetch_array($res))
      {
             echo $data['id'];
             echo $data['left(content, 100)'];
             echo $data['title'];
             echo "<\br>";
      }
?>

Saturday, July 10, 2010

how to search string from text file in php

search string from text file in php or find string from text file in php
Note: In this file we store ( write ) all string ( value ) in text ( txt ) file. And searching string start from "name:", "address" and mend with ";".

Note: Save bellow string for search in "test.txt" file.

Hi my name:Kamran; and address:Delhi;. Working as a Software Developer and my area of expertise in PHP and Java/J2EE and I would like to work in software company providing cutting edge PHP and Java base web application.
In this file I am searching string in php name:ahmad; and address:delhi; with php program bellow. searching string from text file in php.

Note: Save bellow file "searchstring.php".
Note: Remove "\" every place from program

<\?php
    $filename = "test.txt";
    $fp = fopen($filename, "r") or die("couldn't open $filename");
    while(!feof($fp))
    {
        $char = fgets($fp);
        $name = strstr($char,'name:');
        $name1 = substr($name, 5);
        $name2 = strpos($name1, ';');

        echo $name3 = substr($name1, 0, $name2);
        echo "<\br>";

        $address = strstr($char,'address:');
        $address1 = substr($address, 8);
        $address2 = strpos($address1, ';');

        echo $address3 = substr($address1, 0, $address2);
        echo "<\br>";
    }
?>