Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Tuesday, August 31, 2010

Mysql insert multiple/batch of rows using single query

You don't need to loop a mysql insert query to add multiple records to a table. mysql insert support multiple inserts in one query.

Let say you have a table called students with two fields fname and age.

insert into students (fname, age) values
('Kusal', '26'),
('Tom', '18'),
('Ann', '23')

Remember to give the column names in the query.

Monday, August 23, 2010

Best way to get all rows in a mysql table - mysql_num_rows() or count()

Normally there are two ways to get the total number of rows in a mysql table.

$result = mysql_query("select count(id) from table");
$data = mysql_fetch_array($result);
$all_rows = $data[0];

Or

$result = mysql_query("select id from table");
$all_rows = mysql_num_rows($result);


As you have guessed the best server resource friendly method is to use mysql count() function instead of returning all the rows as a result-set to use in php mysql_num_rows() function.

Sunday, August 1, 2010

php post content-length exceeds - post_max_size

1) If you have access to the php.ini file there is a easy fix, just edit the post_max_size line with a higher value you want.

2) If you do not have access to the php.ini file you can create a text file and name it as php.ini (remember to check if the file extension is .ini not .txt) and put this line inside:
post_max_size = 15M
save and upload to the folder where your php script is placed.

(I have used 15M, you can put any value you want)

It is also better to have a chat with your hosting technical help team.

Saturday, July 31, 2010

How to loop through a php assoative array

Looping through a php assoative array is really easy with foreach loop.

<?php

$array = array ("Fruit" => "Apple", "Animal" => "Dog", "Number" => 1, "Name" => "Jhon" );

foreach($array as $key => $value)
{
    echo $key.': '.$value;
    echo '<br />';
}

/* result

Fruit: Apple
Animal: Dog
Number: 1
Name: Jhon

*/

?>

Wednesday, July 21, 2010

How to get number of characters of a String in php - strlen()

You can use strlen() to easily find the length of an php string.

<?php
$str = 'Hello World';
echo strlen($str); // 11
?>

Many new php developers make the mistake of using count() which is used to count elements in an array or properties in an object.

Tuesday, May 19, 2009

Create Dynamic Images with Text Using PHP GD

First check weather php gd library is enabled.


<?PHP

echo '<pre>';

print_r(gd_info());

echo '</pre>';

?>


If you get a error or a blank page that means the gd is not enabled in your server.
Contact your hosting and ask for php gd to be enabled.

Try following coding, everything is commented.


<?PHP

//save the arial.ttf font file in the same folder
$font = 'arial.ttf';
$fontsize = 10;

$YourText = 'Hi This Work';
$Text_Box = imagettfbbox($fontsize, 0, $font, $YourText);

//create image width 250, height 100
$image = imagecreatetruecolor(250,100);

//0,0,0 is black
$bgcolor = imagecolorallocate($image, 0, 0, 0);
//255, 255, 255 is white
$fontcolor = imagecolorallocate($image, 255, 255, 255);

//create a rectangle with the back ground coloe
imagefilledrectangle($image, 0, 0, 250, 100, $bgcolor);

$x = 10;
$y = 20;
//draw text on image
imagettftext($image, $fontsize, 0, $x, $y, $fontcolor, $font, $YourText);

//setting png headers
header('Content-type: image/png');
//create png image
imagepng($image);
//delete tempory files
imagedestroy($image);

?>



You can use this php file in a html file like this also


<img src="your_file_name.php" />

Tuesday, May 12, 2009

Use Gmail to send mails in php

You can use Gmail SMTP to send emails remotely even in your localhost machine with WAMP.
First you must download phpmailer
After you extratced all zip files goto examples folder. In there you will find test_smtp_gmail_basic.php file. Just edit the code with your gmail username and password and you are ready to go.

Before executing the script goto php.ini file and remove the ; that is infront of extension=php_openssl.dll

Then restart your server.

Leave a comment if you need any help.

Monday, May 4, 2009

How to search an array in php

You can use array_search() function to easily search values in an php array. If you didn't know about this function you should have probarbly used a foreach or for loop to find a matching value in your array.

array_search() will return the array key if found the given value. This function is case sensitive to strings.


<?php

$my_array = array('1', 'kuppiya', 'Tom', 'Hello');

$key = array_search('Tom', $my_array);

if($key === false)
{
echo 'Not found';
}
else
{
echo $my_array[$key];
}

?>

Saturday, April 11, 2009

List of Browser User Agents to use with php curl

Here is a simple list of user agents that can be used with php curl or JavaScript

(In windows)

IE 7 - Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; SU 3.21; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)

Chrome - Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.19 (KHTML, like Gecko) Chrome/1.0.154.53 Safari/525.19

Firefox 3.0 Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.8) Gecko/2009032609 Firefox/3.0.8

Firefox 2.0 - Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6

Safari - Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.28 (KHTML, like Gecko) Version/3.2.2 Safari/525.28.1

Opera - Opera/10.00 (Windows NT 5.1; U; en) Presto/2.2.0

Wednesday, April 1, 2009

Get php time diff (time diffence)

Following code will show you how to get time difference in second from a two datetime values. Remember datetime should be in this format: yyyy-mm-dd hr:min:sec

$dbdate_seconds = strtotime($dbdate);
$inputdate_seconds = strtotime($inputdate);

$time_diff = $dbdate_seconds - $inputdate_seconds;

//you will get the time difference in seconds, divide by 60 to make it minutes

or you can use the mysql TIMEDIFF

$query = select TIMEDIFF(field_name, '$input_date') from tbl_name where condition

Wednesday, March 25, 2009

Notice: Undefined index: (php)

Notice: Undefined index:
Sometimes you get this notice (This is not a error). lets see a example why you get this notice or warning.


<?php

error_reporting(E_ALL);

echo $name= $_POST["name"];
echo $number= $_POST["number"];

?>

<html>
<body>
<form name="form1" method="POST" action="">
<table border="0">
<tr>
<td>Name :</td>
<td> <input type="text" name="name" /></td>
</tr>
<tr>
<td>Tel: Number :</td>
<td> <input type="text" name="number" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="sub" value="Add" /></td>
</tr>
</table>
</form>
</body>
</html>



When you initially load this page you will get a notice like following.
Undefined index

This notice is shown because your php.ini file has enabled Notices to display or you may have a set error_reporting() function to E_ALL or to display notices.

The reason for the notice because when the page is load it search for the $_POST["name"] and $_POST["number"] which actually not available, $_POST indexes are set when you submit the form not when you just load the page.

Solutions:
1) you can fix the error reporting levels in php.ini or by error_reporting() function.

or

Change the code like this.


if(isset($_POST['sub']))
{
echo $name= $_POST["name"];
echo $number= $_POST["number"];
}


This will make the code run only when you submit the add button.

Monday, December 15, 2008

How to find the power of a number (Exponential) using php

Following code will show you how to find the power of a number using php.
The function used to do this is pow() function.
pow(base, exponent)


<?php

//first parameter is the base
//second parameter is the exponent

echo pow(2, 2); // 4
echo pow(2, 3); // 8
echo pow(3, 2); // 9

?>



Get custom programming done at GetAFreelancer.com!

Wednesday, November 26, 2008

How to get the Square root of a numeric value using php - sqrt()

Following code will show you how to get the Square root of a given numeric value.


<?php

echo sqrt(4); // 2

echo sqrt(12); // 3.4641016151378

echo sqrt(16); // 4

echo sqrt(17); // 4.1231056256177

?>


Get Free Sinhala IT Learning Videos Kuppiya.com


Get custom programming done at GetAFreelancer.com!

Tuesday, November 25, 2008

How to round a floating point number in php - round()

Following code will show you several examples on how to round a floating numeric value as you like.


<?php

echo round(10.8); // 11
echo '<br />';
echo round(10.4); // 10
echo '<br />';

/*you can also set the number of precision,
or in other words number of decimal digits
you like to round the floating number
*/

echo round(10.837, 2); // 10.84
echo '<br />';
echo round(10.435767, 4); // 10.4358
echo '<br />';

?>


Get Free Sinhala IT Learning Videos Kuppiya.com


Get custom programming done at GetAFreelancer.com!

Monday, November 24, 2008

How to create a dynamic pdf file using php - FPDF fpdf.org

If you need to create dynamic or on the fly pdf files using php, usually we use PDFlib library. but PDFlib library sometimes not available in all hosting packages.
FPDF is a good alternative for PDFlib library, FPDF is a Free php class that you can easily include in you php code, really easy and simple to use FPDF is my choice when creating pdf files on the fly.

www.fpdf.org

Get Free Sinhala IT Learning Videos Kuppiya.com


Get custom programming done at GetAFreelancer.com!

Monday, November 10, 2008

How to search/scan files inside a directory using php - scandir()

Lets see how we can scan or search files inside a directory using php. You can use scandir() for this matter. scandir() will go through the given directory and return all the files in an array.


<?php

$dir_path = 'kusal/test'; //directory path
$list_files = scandir($dir_path);

//dumping the array
//hope you know how to access an array
echo '<pre>'; //html <pre> tags will format the output
print_r($list_files);
echo '</pre>';

/*
Output look like this

Array
(
[0] => .
[1] => ..
[2] => TextDocument.txt
[3] => kuppiya.doc
[4] => lion.ppt
[5] => test.as
)

*/

?>



Get Free Sinhala IT Learning Videos Kuppiya.com


Get custom programming done at GetAFreelancer.com!

Friday, November 7, 2008

How to delete a directory using php - rmdir()

Lets see how can we delete a folder using php.
You can use rmdir() function to do this task, before using this function you should remember that you can only delete empty folders


<?php

$path = 'path to directory'

//First Check if deleting a directory
if(is_dir($path))
{
//remove directory
if(rmdir($path))
{
echo 'Deleted';
}
else
{
echo 'error';
}
}
else
{
echo 'Not a directory';
}
?>


Get Free Sinhala IT Learning Videos Kuppiya.com

 Subscribe To My Blog

Monday, October 27, 2008

How to convert a string into a lowercase letters (simple letters) using php

Following code will show you how to convert a string of letters into lowercase(simple) using php strtolower() function.


<?php

$my_string = "This STRING has UPPERCASE letters";
$my_string = strtolower($my_string);
echo $my_string;

//Output: this string has uppercase letters

?>



Get Free Sinhala IT Learning Videos Kuppiya.com

 Subscribe To My Blog

Sunday, October 19, 2008

How to validate a date to see if its a correct date format using php

You have function called checkdate() where you can validate a input date is actually a correct date format. checkdate() will validate Gregorian date, so we need to properly give the parameters for the checkdate() function.
checkdate($month, $day, $year) - will return true or false


<?php

//checkdate($month, $day, $year) - format

$month = 10;
$day = 12;
$year = 2008;

echo 'Valid Date Example: ';

if(checkdate($month, $day, $year))
{
echo 'Date is correct';
}
else
{
echo 'Date is incorrect';
}

echo '<br /><br />';
echo 'Invalid Date Example: ';

//Invalid date
$month = 14; // month is wrong
$day = 12;
$year = 2008;

if(checkdate($month, $day, $year))
{
echo 'Date is correct';
}
else
{
echo 'Date is incorrect';
}

?>


Get Free Sinhala IT Learning Videos Kuppiya.com

 Subscribe To My Blog

Wednesday, October 15, 2008

How to join array elements together using php - implode()

Lets see how we can join elements in a array to a comma separated String (You can use any separator you want with implode().)
simply use implode and you are done


<?php

$array_items = array('item1', 'item2', 'item3');
$string_with_comma = implode(",", $array_items);

echo $string_with_comma; // item1,item2,item13

?>


Get Free Sinhala IT Learning Videos Kuppiya.com

 Subscribe To My Blog