Category Archives: php
Php export data from mysql to excel
Php export data from mysql to excel : We sometimes need a script in php which can export the mysql table’s data into csv, excel or in some other format. Here in this tutorial we are going to create a script which will export the table’s data into excel file. In this tutorial we will go step by step with example and demo. You can download the complete script free.
Php export data from mysql to excel
Here are steps to export data from mysql to excel using PHP Script.
Table
First specify the table from which you want to export data in excel. Here we have created a script to create table in mysql. First of all please run the below script to create the table and insert the sample data so that we can proceed for php code which will pull data from this table and export it into the excel file.
Create My-Sql Table:
CREATE TABLE IF NOT EXISTS `test_user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL, `email` varchar(50) NOT NULL, `phone` varchar(15) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=8; -- -- Dumping data for table `test_user` -- INSERT INTO `test_user` (`id`, `name`, `email`, `phone`) VALUES (1, 'John', 'johnk@yopemail.com', '121323232'), (2, 'Kelly', 'kellyk@yopemail.com', '121212122'), (3, 'Ryan', 'ryank@yopemail.com', '22222212'), (4, 'Kojo', 'kojao@yopemail.com', '12144444'), (5, 'Kinjal', 'kinjal@yopemail.com', '22555212'), (6, 'Jonny', 'jonny@yopemail.com', '121334444'), (7, 'Barak', 'barak@yopemail.com', '2444444512'), (8, 'Uman', 'uman@yopemail.com', '12334444'); |
After running the above query in mysql you will have a table named test_user with above sample data.
Php Script To Export Data from Mysql Table to Excel File
Here we have created simple script to export data from mysql table to excel file-
Php Script To Export Data from Mysql Table to Excel File & Download:
'; $no++; } ?>
|
Headers header(“Content-type: application/vnd-ms-excel”); & header(“Content-Disposition: attachment; filename=”.$fileName.”.xls”); are used to download convert the plain data in excel format and save it.
You can try and download the full code from the above link provided along with the try it button.
PHP script to detect mobile devices
PHP script to detect mobile devices : You can detect the mobile devices using the php script. Here is an example of getting mobile devices which uses user agent and pattern to match the mobile device.
PHP script to detect mobile devices
Php function to get mobile devices –
PHP script to detect mobile devices
function isMobileDevice() { $match = preg_match("/(android|avantgo|blackberry|bolt|boost|cricket|docomo|fone|hiptop|mini|mobi|palm|phone|pie|tablet|up\.browser|up\.link|webos|wos)/i", $_SERVER["HTTP_USER_AGENT"]); return $match; } |
The function will return true if mobile device found else it will return false.
PHP htmlentities function
PHP htmlentities function : This function coverts all applicable characters to the HTML entities. It accepts string as input parameter and returns the encoded string.
Let us understand the htmlentities with very basic example – Suppose you have a form and it has a text field textarea and user posts data using this field and you want print each and everything user submits using the form textarea. Suppose he enters raw data like this – <b>Hi its me John</b> now what would happen when user see form data on browser it will show something bold string like this – Hi its me John which is wrong because it should show output like this – <b>Hi its me John</b>.Now to fix this problem convet HTML tags to its equivalent entities. This is done by using the function htmlentities().
for example if you use this –
$string = "Hi its me John"; echo htmlentities($string);
Equivalent html entities will be –
This will print the output by converting them in entities like – <b>Hi its me John</b<
.
We are going to explain this function with example and demo.
PHP htmlentities function Syntax
Here is syntax for htmlentities-
:
htmlentities(string,flags,char-set,double_encode); |
Input Parameters
Desription about input parameters of htmlentities-
- string: This is required input parameter which needs to be encoded.
- flags:This is optional input parameter which handles single and double quotes. Here are following quote style-
- ENT_COMPAT : This is default. Converts/Encodes only Double Quotes
- ENT_QUOTES : This Decodes Both Single and Double Quotes.
- ENT_NOQUOTES : Encodes neither Single nor Double Quotes.
- char-set: This is optional parameter. This is basically used to decide which character set to use.
- UTF-8 : This is Default ASCII Compatible Multi byte 8-bit Unicode.
- ISO-8859-1 : Western European, Latin-1.
- ISO-8859-15 : Western European, Latin-9
- cp866: DOS-specific Cyrillic charset
- cp1251 : Windows-specific Cyrillic charset.
- cp1252 : Windows specific charset for Western European
- KOI8-R : Russian.
- BIG5 : Traditional Chinese, Specially used in Taiwan.
- GB2312 : National standard character set.
- BIG5-HKSCS : Traditional Chinese.
- Shift_JIS SJIS, SJIS-win, cp932, 932 Japanese
- EUC-JP :Japanese
- MacRoman : Charset that was used by Mac OS.
- double_encode: This is optional parameter which decides whether to encode existing htmlentitis or not. It accepts TRUE and FALSE as parameter.
- TRUE: Convert Everything.
- FALSE: Do not convert existing htmlentities.
Return Parameter
Returns the encoded string on the basis of the flags,char-set and double_encode parameters which are optional but plays and important role while encoding process. Here are some example which will make the things more clear about the PHP htmlentities function.
PHP htmlentities function
Here is very basic example of htmlentities function-
html entities function Example:
$string = " |
If you run the above example it produce the following output as below-
The browser output will be something like this-
More Examples
Let’s have look over more example and demo here.
htmlentities Example with ENT_COMPAT,ENT_QUOTES & ENT_NOQUOTES
htmlentities Example:
$string = "'Tutorialsplane Learn Easy!' & Learn 'More' here now"; echo htmlentities($string,ENT_COMPAT)." |
The HTML Output of the above example is –
The Browser Output of the above example is –
If You want reverse of this function just use –
Learn More – html_entity_decode function
Secure Your Application Using htmlentities
Let us take a very important example which every developer should know and use while working with input fields and storing them in database and displaying them on front end.
Consider you have used htmlentities while displaying data in front end and someone inserts a few lines of javascript to redirect to some other location such as –
Unsafe Data in Html:
|
What would happen if this code is not encoded ?? it will consider that you have inserted above piece of javascript in html which will always redirect to the given url instead of printing the above code.
To fix the above problem use htmlentites which convet HTML tags to entities and will print instead on redirecting.
If you use html entities it will convert the above code as –
So now your html data is secure which will now print the below data instead of redirecting to another url-
Php 5 String Functions Reference
Php 5 String Functions Referencee : Here is the list of Php 5 String Functions
Php 5 String Functions Reference
[table caption=”Php 5 String FUnctions” width=”100%” colwidth=”20|100|200|200″ colalign=”left|left|left|left|left”]
no,Function,Description,Detail,Demo
1,addcslashes(),It Adds the backslash before the specified string,More Detail & Demo», Demo »
2,addslashes(),It adds backslash(\) before each single quote(‘) and double quote(“) in string,More Detail & Demo», Demo »
3,bin2hex(),bin2hex() converts the binary string to hexadecimal string,More Detail & Demo», Demo »
4,chop(),used to remove the whitespaces or predefined character from right,More Detail & Demo», Demo »
5,chr(),is used to convert an ASCII number to character,More Detail & Demo», Demo »
6,chunk_split(),chunk_split() Function splits the string in series of smaller parts.,More Detail & Demo», Demo »
7,convert_cyr_string(),Is Used to convert one character set to another character set.,More Detail & Demo», Demo »
8,convert_uuencode(),convert_uuencode() is used to encode a string using the uuencode algorithm.,More Detail & Demo», Demo »
9,convert_uudecode(),It is used to decode a string using the uudecode algorithm.,More Detail & Demo», Demo »
10,count_chars(),count_chars() Function splits the string in series of smaller parts.,More Detail & Demo», Demo »
11,crc32(),crc32() It creates the 32-Bit Cyclic redundancy checksum of a string.,More Detail & Demo», Demo »
12,crypt(),crypt() It encrypts the string using the DES Blowfish or MD5 algorithms.,More Detail & Demo», Demo »
13,echo(),echo() It Echo function is used to print the strings in php..,More Detail & Demo», Demo »
14,explode(),explode() converts string to array.,More Detail & Demo», Demo »
15,html_entity_decode(),html_entity_decode() It converts the html entities to its applicable characters,More Detail & Demo», Demo »
16,htmlspecialchars_decode(),htmlspecialchars_decode() It converts Some HTML entities to its characters equivalent.,More Detail & Demo», Demo »
17,htmlspecialchars(),htmlspecialchars() It converts Special Characters to HTML entities.,More Detail & Demo», Demo »
18,Implode(),htmlspecialchars_decode() It converts array into string.,More Detail & Demo», Demo »
19,number_format(),This function is used to format a number with grouped thousand.,More Detail & Demo», Demo »
20,number_format(),Is used to pad a string to new length with another string.,More Detail & Demo», Demo »
[/table]
Php json decode array example
Php json decode array example
Php json decode array example
$json = '["apple","orange","banana","mango"]'; $array = json_decode($json); foreach($array as $item){ echo $item."
"; }
which will produce the following result;
// apple
// orange
// banana
// mango
Php implode array by newline
Php implode array by newline : You can use PHP_EOL to implode array by line break.
Php implode array by newline break
$array = implode(PHP_EOL, $array);
Which will break the string at the break line.
Php explode array at line break Example
$array = array('a','b','c'); $string = explode(PHP_EOL, $array); echo $string; // will produce // a // b // c
Php explode string by newline
Php explode string by newline : You can use PHP_EOL to explode string at line break.
Php explode string by newline break
$array = explode(PHP_EOL, $string);
Which will break the string at the break line.
Php explode array at line break Example
$string = " str1 str2 str3"; $array = explode(PHP_EOL, $string); print_r($array); array('0'=>'str1','1'=>'str2','2'=>'str3');
Facebook style cover image reposition in php jquery
Facebook style cover image reposition in php jquery : In this post we are going to explain the functionality implemented just like facbook style cover image repostion in php and jquery.
Jquery Ui : Jquery ui is used to enable the draggable functionality for the selected image.
Php : We are using php on sever side to resize and crop the image on co-ordinates provided. Co-ordinates are passed to the server selected by the user.
Jquery Ui Draggable : Provides the draggable functionality on element. Event is triggered when we move mouse on the
element ie image in this case.
Jquery Function used for draggable functionality.
Facebook style cover image in PHP with Syntax
Jquery Ui : Draggable
function initUi(){ $(function(){ $(".coverimage").css('cursor','s-resize'); var y1 = $('.imagecontainer').height(); var y2 = $('.coverimage').height(); $(".coverimage").draggable({ scroll: false, axis: "y", drag: function(event, ui) { if(ui.position.top >= 0) { ui.position.top = 0; } else if(ui.position.top <= y1 - y2) { ui.position.top = y1 - y2; } }, stop: function(event, ui) { //#### $("#top").val(ui.position.top); } }); }); } |
Main page with above code and main layout : index.php
Javascript Code to handle the drag and save event.
|
PHP Code On Server Side : functions.php
Php code to Resize And Crop the image to Fit on container
$h) { $imageHeight = floor(($h/$w)*$width); $imageWidth = $width; } else { $imageWidth = floor(($w/$h)*$height); $imageHeight = $height; } $x = 0; $new = imagecreatetruecolor($imageWidth, $imageHeight); // preserve transparency if($type == "gif" or $type == "png"){ imagecolortransparent($new, imagecolorallocatealpha($new, 0, 0, 0, 127)); imagealphablending($new, false); imagesavealpha($new, true); } imagecopyresampled($new, $img, 0, 0, $x, 0, $imageWidth, $imageHeight, $w, $h); switch($type){ case 'bmp': imagewbmp($new, $dst); break; case 'gif': imagegif($new, $dst); break; case 'jpg': imagejpeg($new, $dst); break; case 'png': imagepng($new, $dst); break; } return true; } function crop($source,$destination,$destinationWidth,$destinationHeight,$x1,$y1){ if(!list($w, $h) = getimagesize($source)) return "Unsupported picture type!"; $type = strtolower(substr(strrchr($source,"."),1)); if($type == 'jpeg') $type = 'jpg'; switch($type){ case 'bmp': $copy = imagecreatefromwbmp($source); break; case 'gif': $copy = imagecreatefromgif($source); break; case 'jpg': $copy = imagecreatefromjpeg($source); break; case 'png': $copy = imagecreatefrompng($source); break; default : return "Unsupported picture type!"; } // this is taken because of maintaining the aspect ratio for the croping to the exact height and width. $w = $destinationWidth; $h = $destinationHeight; $new = imagecreatetruecolor($destinationWidth, $destinationHeight); imagecopyresampled($new, $copy, 0, 0, $x1, $y1, $destinationWidth, $destinationHeight, $w, $h); switch($type){ case 'bmp': imagewbmp($new, $destination); break; case 'gif': imagegif($new, $destination); break; case 'jpg': imagejpeg($new, $destination); break; case 'png': imagepng($new, $destination); break; } return true; } ?> |
Main crop.php handling the complete server process :
Php ini_set display_errors
Php ini_set display_errors
You can eanble error reporting in php as below :
Add the following code in the top of your file.