Tuesday, 26 April 2016

EXPORT DATA TO EXCEL IN PHP

Question: I have recently made a website and have a members table in my sql. I have an admin page that has the ability to download that with column names; however I used to use INTO OUTFILE but that is not allowed on my host. I came up with this code to download the file:
<?php
if(file_exists('downloads/members_'.date("m-d-Y").'.csv') == true){
    header("Location: /downloads/members_".date("m-d-Y").".csv");
} 
$output=fopen('downloads/members_'.date("m-d-Y").'.csv','w+');
fputcsv($output,array(
                 'memberID','username','password','email',
                 'active','resetToken','resetComplete',
                 'support','supportToken'
             )
);
$rows =mysql_query("SELECT * FROM members;");
while($row=mysql_fetch_assoc($rows))
    fputcsv($output,$row);
header("Location: /downloads/members_".date("m-d-Y").".csv");
exit;
?>

This just outputs the column names and I have never used fputcsv before and am a tad confused on what I am doing wrong. I get the file to download but not with the table in it.
[EDIT] I just tried it with a valid sql query and it does not work. updated code above. Also There is stuff in the members table.
Answer: Try this and read the comments carefully:
<?php
try {
    /**************************************
    * Create sqllite3 database and        *
    * open connections                    *
    * Coded by Mawia HL for SO Answer     *
    **************************************/ 
    // Create (connect to) SQLite database in file
    $file_db = new PDO('sqlite:messaging.sqlite3');
    // Set errormode to exceptions
    $file_db->setAttribute(PDO::ATTR_ERRMODE, 
                            PDO::ERRMODE_EXCEPTION);
    $file_db->query("CREATE TABLE IF NOT EXISTS `members` (
               member_id INTEGER PRIMARY KEY, 
               username TEXT, 
               password TEXT, 
               email TEXT, 
               active TEXT, 
               resetToken TEXT, 
               resetComplete TEXT, 
               support TEXT, 
               supportToken TEXT
            )");
     $insert = "INSERT INTO members (member_id, username, password, 
                  email,active,resetToken,resetComplete,support,supportToken) 
         VALUES ('1', 'John', 'john123', 'john@gmail.com','2','4757ghf',
                '657hfd','657hdhd','857tydhdn')";
     $file_db->query($insert);
}catch(PDOException $e) {
    // Print PDOException message
     echo $e->getMessage();
  }
function getRow($result) {
     return $result->fetch(PDO::FETCH_ASSOC);
}
if (isset($_POST['download'])) {
    $result = $file_db->query('SELECT * FROM members');
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment;filename=yourcsv.csv');
    header('Cache-Control: no-cache, no-store, must-revalidate');
    header('Pragma: no-cache');
    header('Expires: 0');
    $csvoutput = fopen('php://output', 'w');
    $row = getRow($result);
    $headers = array_keys($row);//columns from db e.g, memberID','username',...
    fputcsv($csvoutput, $headers);
    fputcsv($csvoutput, $row);
    while ($row = getRow($result)) {
        fputcsv($csvoutput, $row);
    }
    fclose($csvoutput);
    exit;
   }
$listing = $file_db->query('SELECT * FROM members');
?>
<h1>Members Listing</h1>
    <?php while ($row = getRow($listing)) { ?>
    <h2><?php echo $row['member_id']; ?></h2>
    <ul>
        <li>Member Name: <?php echo $row['username']; ?></li>
        <li>Password: <?php echo $row['password']; ?></li>
        <li>Email: <?php echo $row['email']; ?></li>
        <li>Active: <?php echo $row['active']; ?></li>
    </ul>
   <hr>
    <?php } ?>
   <form method="post">
        <fieldset>
            <legend>Download Results in CSV Format</legend>
            <p>
                <input type="submit" name="download"
                    id="download" value="Download File">
            </p>
        </fieldset>
    </form>

Here is real-time demo with sqllite3 database. Uncomment the create database and insert statement in order to see the working demo. I am using sqllite3 because it is testable online. You can easily integrate it in mysql database or any other databases.

Namespaces in PHP

Introduction

PHP-ah hian Best Practice (Hmandan tunlai ber) tih hi sawi a awm ta fo mai a. Chutiang best practise huangah chuan NAMESPACES hi hmaih thiang lo khawp a pawimawh a ni a. Mawl te, zir tan te tana hriat fuh har ve fu si hi a ni a. Best practice han tih hian mithiam zawkte'na code dan kalphung tha bera an ngaih leh chin zui tlaka an ngaih an sawina ni berin kei chuan ka hria a. Thiam inti ve tak te chuan thenkhatin best practise an tih pawh kha best practise a ni lo ve thei tho bawk a ni. Namespaces an tih chu enge a nih a, kan hun leh tha, sum leh pai ngaihtuahin chin zui tlak a ni dawn em tih te, kan mamawh ve dawn em tih te i lo en dawn teh ang.

Definition

PHP.NET (php document inpui) ka thlir changa ka nin deuh mai chu an ziahna tawngkam vel hi a ni. Hriatthiam awl taka ziak ve mai ta lo hian technical em em hian an ziak thin a, ngeiawm ve mai mai! Mahse, PHP chungchang kan sawi dawn chuan kan rawn ber a ni lo thei si lo. Awle, PHP documentation-in Namespaces awmzia a hrilhfiah dan hi i lo en phawt teh ang.
What are namespaces? In the broadest definition namespaces are a way of encapsulating items. This can be seen as an abstract concept in many places. For example, in any operating system directories serve to group related files, and act as a namespace for the files within them. As a concrete example, the file foo.txt can exist in both directory /home/greg and in /home/other, but two copies of foo.txt cannot co-exist in the same directory. In addition, to access the foo.txt file outside of the /home/greg directory, we must prepend the directory name to the file name using the directory separator to get /home/greg/foo.txt. This same principle extends to namespaces in the programming world.

Mizo tawngin:Namespaces hi enge? Thil(code items) thliar hranna siamtu tiin huapzau awmzia kan neihtir thei a. Hei hi Programming kalkawng tinah mitthla tur a awm thei ang. Entirnan, OS hrang hrang (Windows, Macintosh, Linux, etc.) ah te hian directory(folder) hrang hrang kan nei thluah a, folder chhungah khan file kan nei leh thluah thei bawk a. Tichuan folder chhunga file te tan folder kha an namespaces a ni. A ruh langin lo sawi ta ila, file pakhat foo.txt chu /home/greg folder leh /home/other folder chhungah a awm ve ve a. /home/greg chhunga foo.txt hawng tur chuan /home/greg/foo.txt (a file hming a tawpa dahin) hmangin ka hawng thei a. Hetiang chiah hian programming khawvelah namespaces hi hman a ni ve bawk.

PHP Language-ah

PHP-ah chuan Namespaces hi Libraries leh Application siamtute'n hman nawn theih tura code elements: classes leh functions an siam laia buaina an tawh thin chinfel nana ruahman (designed) a ni.
  1. Kan code ziah-a hming in ang thliar hran nan. Third Party libraries leh function te khan kan function leh class hming ang chiahin function leh class hming an lo nei ve thei a. Midangin kan hming hman ang hmang mahse namespaces hmangin a thliar hranna awlsam tein kan siam thei tihna a ni.
  2. Class leh function hming sei pui pui tihtawina leh chhiar nuam zawka dahna a ni bawk.

Examples:

Entirna nen hian lo sawifiah ila a chiang zawk awm e:
function con( )
{ 
       echo ‘Connecting to Members’; 
}
A chunga mi ang hian function ka lo siam ta a, ka siam ang chiah hian library leh code dang ka hman te khan an lo siam ve theih avangin a pumpelh nan mahni phuahchawp liau liau namespace siamin function zz_db_connect(){ } tiin zz chu namespace leh db sub-namspace atan ka hmang ta a, hei hian hming in ang awm thei(name collisions) lakah ka code chu a humhim thei a ni. Mahse hei aia namespaces siam dan tha zawk kan nei thei a, chu chu kan thupui ber namespaces hi a ni. Code example tlem lo tarlang ve ila:
//index.php:
<?php
require_once ('func.php');
echo con();//Output: Connecting to Members
?>
A hnuaia mi ang hian func.php chu:
//func.php
<?php 
function con( )
{ 
       return 'Connetion to Members'; 
}
?>
A chunga code-ah hian index.php-ah func.php-a kan database connection chu kan lalut a. Hei hi namespaces-ah kan chantir dawn chuan a hnuaia mi ang hian tihtur a ni ang:
//func.php
<?php namespace ZZ\DB;
function con( )
{ 
       return 'Connetion to Members'; 
}
?>
tiin kan dah thei ang. Mahse index.php hi kan run chuan error a lo lang ngei ang. Chuvangin index.php-ah hian eng emaw kan thlak ve a ngai dawn a ni. Eng tak ni ang maw? Awle hetiang hian kan index.php chu kan thlak ve a ngai ang.
//index.php
<?php
require_once ('func.php');
echo ZZ\DB\con( );
?>
A chunga kan hmuh ang hian namespaces kan siam kha kan hman chhuahnaah pawh kan hman leh a ngai dawn tihna a ni. Mahse hei pawh hi function kan ngah chuan chhut ve zel a ngaih dawn avangin a lo tha tawk chuang lo. Entirnan, func.php-ah khan function query( ){ 'SELECT data'; } te hi lo neih belh leh ta ila, index.php-ah kan hman chhuah dawn chuan index.php chu a hnawk chho nghal ang:
//index.php:
<?php
require_once ('func.php');
echo ZZ\DB\con( );
echo ZZ\DB\query( );
?>
Kan hmuh ang hian ZZ\DB kan hman ve zel ngai lo hian index.php page-ah a chungber php(<?php) tag hnuaiah chiah khan namespace ZZ\DB; tiin namespace kan hawng thei a ang. Tichuan ZZ\DB hi hman nawn sek ngai lovin kan function(class pawh nise) an hming put ang ang khan kan hmang thei dawn a ni. Tichuan index.php thar chu:
//index.php
<?php
namespace ZZ\DB;
require_once ('func.php');
echo con( );
echo query( );
?>
Tih dan dang awm leh thei chu use keyword hman hi a ni. use keyword kan hman chuan a sub-namespace kha function-ah kan beitir zel a ngai thung ang. Entirnan:
//index.php:
<?php
require_once ('func.php');
use ZZ\DB;
echo DB\con( );
echo DB\query( );
?>
References:
  1. Namespaces in php
  2. Namespaces Overview
  3. Defining Namespaces

Saturday, 23 April 2016

printf() in PHP

Thil ziahchhuah (Text Output) nan echo() function leh print() function hi PHP-ah chuan hman tam ber a ni thin a. Mithiam zawk te chuan print aiin echo hi a performance tha zawkin an tarlang a. Tun tumah hian kan hman tam lutuk loh thilziah chhuah(text output)-na hmanraw changkang deuh zawk printf chungchang inthlahrung takin in sawi lang ve leh dawn teh ang.
printf () hi print format tihna a ni a, kan output tur format-na a ni. Entirna nen lo tarlang ila a chiang leh zual ngei ang:
E.g. 
printf("There are %d items in your basket", 3);

Example-a kan hmuh ang hian printf chuan argument pahnih a nei a. %d hi specifier an ti a, format-na hmanrua ber a ni a, Kan argument pahnihna `3` hi kan format tur string a ni. Argument hi Specifier kan neih ang zat zat kan nei thei bawk a ni. Specifier hrang hrang te chu:
  • % : % character
  • b : Binary integer-a dahna
  • c : ASCII character-a dahna
  • d : Signed decimal integer-a dahna
  • e : scientific notation-a dahna
  • f : floating-point-a dahna
  • o : octal number-a dahna
  • s : string-a dahna
  • u : unsigned decimal-a dahna
  • x : lowercase hexadecimal-a dahna
  • X : uppercase hexadecimal-a dahna
Argument leh specifier hi a inzat chhung chuan specifier hi duh zat zat neih theih a ni a, mahse % symbol hi a hmaah dah zel tur a ni. Entirnan:
E.g.
printf("My name is %s. I'm %d years old, which is %X in hexadecimal",'Sir Sama', 33, 33);
//Output: "My name is Sir Sama. I'm 33 years old, which is 21 in hexadecimal".
Warning: Argument pakhat lek pawh i hmaih chuan parse error a awm nghal ang a. ') was unexpected encountered' tih ang vel error a lo awm ang.
Hmanna dang:
1.
printf("<span style='color:#%X%X%X'>Hello</span>", 65, 127, 245);

Output: <span style='color:#417FF5'>Hello</span>

Hrilhfiahna: hetah hian color red=65, green=127, blue=245 chu hexadecimala convert buai ngai lovin printf hmangin awlsam zawkin kan convert thei a ni.
2.
printf("The result is: $%.2f", 123.42 / 12);

Output
: The result is $10.29
Hrilhfiahna
: Pawisa (currency) hi 2 digit precision nei vek tura ngaih a ni a, mahse calculation a tam chuan digit 3/4 te a ni chho mai thin a, chumi pumpelh nan chuan %.2f hmangin 2 digit chauh hmang turin kan siam thei a ni. Hei hi number_format() hmang pawhin tihtheih a ni tho bawk a ni.
3.
printf("The result is $%15f\n", 123.42 / 12);

output
: The result is $ 10.285000
Hrilhfiahna: %15f\n hian $ leh kan number inkarah 15 space a dah a ni.
Real World Example:
//id: integer, max width 10
//code: string max width 2
$records =$mysqli->query("SELECT id, code from country");

$divider=printf("+%-10s+%-13s+",'-','-');

$lines[]=$divider;

$lines[]=printf("|%10s|%13s|",'id','countryCode');
//header
$lines[]=$divider;

while($line=$records->fetch_assoc()) {
//store the formatted output
   
$lines[]=printf("| %10u | %2.2s |", $line['id'],$line['code']);

}
$table=implode("\n",$lines);
echo
$table;
Output:
+----+-------------+
| id | countryCode |
+----+-------------+
| 1 | ES |
| 2 | AN |
| 3 | AF |
| 4 | AX |
| 5 | AL |
| 6 | DZ |
| 7 | AS |
| 8 | AD |
| 9 | AO |
| 10 | AI |
+----+-------------+

Saturday, 2 April 2016

Stackoverflow hi ka inzirna hmun

Stackoverflow hi khawvela programmer zawhna leh chhanna community lian ber a ni a. An kalphung hi ho te a ni a. Mi tu pawhin awlsam tein a thlawnin an zawm thei a. Programming-a an harsatna te an zawt thei a, mi zawhna an chhang thei bawk a. Zawhna chu programming lam a nih ngei ngei a ngai a, code inziahsakna hmun a ni lo va, code dik lo leh bug in solve-sakna hmunpui a ni. Tam tak chuan mawl tak takin zawhna an zawt a, chutiang te chu zawtna zawt thei tawh lo tura block hmak hmak an ni bawk. Zawhna chhanna pawh sawifiahna tlem tal a tel loh chuan vote downa ni tlangpui thin. Zawhna tha leh chhanna tha chuan vote up an hlawh tlangpui bawk a ni.
Kan zawhna leh chhanna tang hian vote hmangin reputation point leh score te pek kan ni a, kan zawhna leh chhanna chu vote down a nih chuan kan point kan hloh ve zel thei bawk a ni. Kan reputation point bakah hian kan score atangin badge hrang hrang kan hlawh leh thei a. badge-ah rau rau pawh tag badge hlawhchhuah hi a awl ai lo hle a ni. Tag badge hi Bronze, Silver leh Gold-ah then hran a ni a, Bronze badge hlawh tur hian kan chhanna tag entirnan PHP-ah khan 100 tal kan score a ngai a ni. Hei hian a entir ber chu PHP language basic chu kan nal ve thawkhat tih a entir ber a ni. Silver badge kan hlawh chuan Intermediate level php Programmer vel kan ni tihna a ni leh ang a, Gold tag badge kan hlawh chuan PHP expert kan ni tihna a ni. Silver badge hlawh tur hian php tag-ah 400 tal score a ngai a, Gold badge hlawh tur hian 1000 tal kan score a ngai bawk a ni.
A chipchiar takin engkim ka sawi hman lo va (hetah hian lo bih la). Ka sawi duh ber zawk chu stackoverflow-ah hian kum 2 leh thla 9 member ka ni tawh a, eng eng emaw vangin ka active thei lo va, member ni reng chung siin member ni lo ang velin kum 2 chu ka hmang liam a, tun hnai thla hnih thum vel hian ka lu ve ta zeuh zeuh a. A bikin tun kar chho phei hi chuan ka awl tawh phawt chuan ka lut ve ta ziah a. He ta ka thil hmuhchhuah chuan nasa takin ka improve tih hi a ni. Zawhna chu ka zawt chiam lo va, mi zawhna ka chhang ber a. Member 4.7 million karah zawhna lo lut chhan inchuh chu a hau tak cher cher khawp mai. Kan chhanna an accept loh phei chuan eng reputation leh point mah kan hlawh chhuak (score) thei bawk si lo. Mahse hetiang zawng hian ka ngaihtuah a, pratice-na ni mai alawm. tiin. Mithiam pui pui kara chhanna lo pek ve chu a inthlahrunawm duh thin kher mai. Buaithlak leh bawk chu chhanna ka ziak tan ve dawn chauh a, mi pahnih pathumin an lo chhang hman zel thin hi a ni. Mahse tim hauh lovin inzir nan tiin ka chhang ve ta zel a. Tichuan hman ni khan unsung Hero (gold Bagde) ka hlawhchhuak ve ta a.

Stackoverflow hian dataquery an lo dah reng mai a: Chhanna ka pek atanga an lo accept dan average chu 34.% vel a ni. Stackoverflow-a points hmu sang ber leh ranking-a pakhatna ni mek Jonskeet chhanna acceptance % chu 60.42% a ni a. 60% pelh hi thil theih loh ang hialin sapho pawhin an sawi a ni.

Stackoverflow-a thil chhinchiahtlak tak mai an dah dang leh chu answer score graph hi a ni.
 Community pumpui kan chhanna that dan (effectiveness) lan tirtu ber chu average answer score hi a ni bawk a. Kei chuan ka la score chhe hle: Ka average score chu 1.05 tih vel chauh a la ni a, Jon Skeet ve thung chu 8.16 vel a ni, a san belh leh tawh mai thei bawk. He data hi a pawimawh hle, kan chhanna a that chuan kan score pawh a pung ve thin a. Miin kan zawhna an accept khan reputation chu point 15-in a pung ngei a, mahse score engmah kan nei lo va, mi dangin kan chhanna kha tha an tih a, an vote up chauh khan score kan nei a ni. Chuvangin Answer pakhat zela 1.05 vel score pawh hi hau tak tak chu a ni. Chhan uluk a ngai a nih ber chu.
A chunga ka sawi bak pawh hi data query atang khan zirchian zel theih a ni a. A pawimawh ber chu mi zawhna kan chhan khan kan hriatna kan tuaithar leh zel tihna a ni a. Chhang dik turin keimahni pawh kan inzir belh ve zel a ngai bawk a ni. Programming eng pawh i tui a nih chuan stackoverflow-a awm hi thil tihmakmawh a ni. Stackoverflow hian reputation 200 (reputation hi point 200 aia tam ni khatah hlawh theih a ni lo) chuang nei chin atangin ranking a siam a, tuna member 5,396,014 atanga ka ranking chu 53277 a ni a. Hmabak a la ko hle mai.

Eng language-ah pawh expert nih i duh chuan Gold Badge hlawhchhuah tum la, i hlawh chhuak thei ngat a nih chuan expert i tihna a ni ang. Reputation tih vel hi chu a hming mai a ni a,  1000 i score theih chuan nasa takin i problem solving skill pawh i improve ngei ang. Stackoverflow site kalphung hi a fel fai hle a, vote abuse vel pawh thiltheih loh a ni a. Entirnan account pathum pali pawh nei la, i ip address leh i voting kalphung hmangin mi pakhat angin i awm reng tho ang. A tir chuan ka awih chiah lo va, reputation abuse tumin account dang te kan hawng vel chhin a, vote ka han inpe sang sang a, a hnu rei lo teah chuan he message hi ka dawng nawlh mai a: This account is temporarily suspended for voting irregularities. The suspension period ends in 7 days. Fake vote chu an paih nghal vek bawk a ni.
My account is suspended due to fake votes
Hei vang hian ni 7 ral hma chu min zawhna pawh ka chhang thei tawh lova, midang zawhna ka chhan tawh, comment hmanga kan inhrilhfiah mek te, zawhna ka chhan theihna te, mi ka vote-up theihna te chu ni 7 chhung tan hman theih lohvin a awm ta hmiah mai a, ka reputation pawh 1-ah lock a ni bawk. Fake vote chu an man thiam khawp mai, khawl dang leh ip dang atang pawh ti mah ila an man nghal chat chat thei a ni. Mahse an fair ve leh na em em chu zawhna kan chhan atanga vote dik tak kan hmuh chu paih a ni dawn lo, tih moderator te'n chat atangin min hrilh a, ka experiment-na a ni a, ka fake reputation kha chu paih vek ula, a ngaiin min kaltir leh rawh u, ka tih pawhin a theih loh thu leh ni 7 hnuah chauh a ngaia ka kal theih tur thu min hrilh a, tun hnua hetiang thil a thleng leh a nih chuan i account pawh remove hial a ni ang tih thlengin min hrilh ta mai a ni. Stackoverflow fair zia chu a takin ka hmu ta a ni.