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

Tuesday, December 15, 2009

System Requirements for running Magento

In order to run magento open source e-commerce software you need the following server requirements.

1)Operating System: Linux servers are only supported servers for magento software.

2)Web Servers: Apache 1.3.x or Apache 2.x or higher version of Apache are only supported versions of web servers for magento.

3)Development Language: Magento only supports PHP and version of PHP must be at least 5.2.0 or above.

4)Database: Mysql is only database language that is supported for magento and version must be 4.1.20 or above.

So your hosting server must support these specification. Before you hosting company check out their specifications. Also you need to enable following extensions.

- curl,
- dom,
- gd,
- hash,
- iconv,
- mcrypt,
- pcre,
- pdo,
- pdo_mysql,
- simplexml.

You can also check your hosting server requirements by following below steps.

1) Download magento-check.zip from http://www.magentocommerce.com/_media/magento-check.zip.

2) After unzipping the file and upload the php file to your Magento directory on the server.

3) In your browser navigate to this page. http://......../magento-check.php
It will say which requirements you are missing.

Related Documents
http://arjudba.blogspot.com/2009/12/magento-installation-does-not-proceed.html

Monday, December 14, 2009

Wordpress or Joomla? Which one to choose?

Wordpress or Joomla? Which one you should use?
Both Joomla and Wordpress have a great demand now a days. The reason is simple- because site built by Joomla and Wordpress are better for SEO results because of their SEO friendly urls. Both of them are Free Open source Content Management systems that will help you manage your websites and also used for templates for the layout of your sites.

To make your blog as well as your website you might also choose one of them. But which one to choose? You first need to ask yourselves what type of website you will build? Here goes typical questions.

- Do you want to blog or build a blogging website? If so then choose wordpress. In case of blogging site you can't beat Wordpress. User, SEO friendly urls, tags feature of wordpress make the blogging job easy.

- Do you want to build a big website with lots of features? If your target is to build a big website with lots of features then choose Joomla. There is so many Joomla templates that make the things easy.

- Do you want to build a small website with small features? If so then choose Wordpress as cms.

- Do you want to build a large community site? If so then go for Joomla.

- Do you want to build a website with multilevel categories? If so then go for Wordpress.

Now let's have an idea about Wordpress and Joomla functions.

Wordpress has dashboard by which you can manage new post, adding categories, changing themes, links etc.

In Joomla control panel is much different than that of wordpress. There is lots of functions already built in Joomla. Once you have gone through the ins and outs of each Joomla and Wordpress you know better what fits for you from a technical point of view.

From my point of view, neither core Joomla nor core wordpress will fit for your needs. So you needs more functions, in other words you need plugins to accommodate your needs. For extra functionalities Joomla! uses three different kind of items, plugins, modules and components whereas WordPress uses Plugins and Widgets.

Joomla Components, Module and Plugins
In Joomla, a component is an extra piece of software that has is own control panel to handle the different options within such a function.

A module is to place some information on a certain position (determined by the template) to show on the front-page.

Plugins are mostly extra functions that create or deliver new back-end functions like a different WYSIWYG Editor.

Wordpress Plugins and Widgets
In WordPress plugins do the same functions as in Joomla, some give your more back-end controls like the Robots Meta plugin or they will have their own Control panel (setting). They comes with extra functions with their extra management panel.

Widgets are more like the Modules in Joomla, you can show pieces of information on a separate position, also determined by the Theme of your WordPress installation.

Whether you use Joomla or Wordpress you should install latest versions of it and you need to upgrade them. In their control panel you can have a look whether any update version is available.

Related Documents

Best SEO tips to increase your website traffic

Sunday, December 6, 2009

Magento Installation does not proceed from Configuration window

Problem Description
While installing magento the first window is License Agreement which says
"

Welcome to Magento's Installation Wizard!

"
After accepting term and clicking continue

Localization

window appears. Clicking continue button brings the window

Configuration

In the configuration window you will see Database Connection, Web access options and Session storage options. After filling forms you may face problem that clicking continue button will not proceed further and also it does  not display any error messages. 

Cause of the Problem
The installation does not proceed because either host, database name, user name or password field value is wrong. If you pass any wrong information to those fields then installation will not proceed. 

Solution of the Problem 
Before proceed installation be sure that host, database name, user name and password field are correct. You can test those from your command line. In mysql database using mysql command line interface try to login using the information that you provided in the magento configuration. If you are successful then be sure that your database name is correct and you can connect that database using your user name and password. 

Also make sure before installation database you must create a database. On your mysql prompt you can do it by simply,

mysql> create database magento;
Query OK, 1 row affected (0.06 sec)

If you want a dedicated user for magento then be sure to create that user too and give permission to that user to access the database.

After you put all right information click continue button and you will see installation proceed. 

Related Documents

Sunday, July 26, 2009

How to retrieve checkbox value from mysql database

In this post I will show you how to retrieve checkbox value from database. As in the database in one field there resides multiple checkbox value so we need to be cautious while displaying checkbox data specially which box to be checked and which not.

Let's assume that field values for method #1 that is described inside http://arjudba.blogspot.com/2009/07/entering-mutiple-values-with-checkbox.html

We assume that checkbox field data are inserted into the database using comma separated values.

BY manually we are doing here for testing purpose.

mysql> delete from checkbox;
Query OK, 2 rows affected (0.00 sec)

mysql> insert into checkbox values('meat,vegetable,fastfood');
Query OK, 1 row affected (0.00 sec)

mysql> select * from checkbox;
+-------------------------+
| foods |
+-------------------------+
| meat,vegetable,fastfood |
+-------------------------+
1 row in set (0.00 sec)

Now following is the php code that is used to display for checkbox. Specially look at the condition,

if (in_array($food,$foods_ex)){
echo "<td>";
echo "<input type=\"checkbox\" name=\"food_cat[]\" value=$food checked>$food</input>";
echo "</td>";
}
else{
echo "<td>";
echo "<input type=\"checkbox\" name=\"food_cat[]\" value=$food>$food</input>";
echo "</td>";
}


<?
include('include/db.php');

$query="select foods from checkbox limit 1";

$result = mysql_query($query);
if(mysql_num_rows($result)>0){
$row = mysql_fetch_array($result);
extract($row);
}
mysql_close();

?>

<html>
<body>
<form method="post">
<table width="50%">
<th>What is your favorite food?</th>
<tr>
<?
$array_food=array('fish','meat','vegetable','fastfood','soup');
$foods_ex=explode(',',$foods);
//print_r ($foods_ex);
foreach($array_food as $food){
if (in_array($food,$foods_ex)){
echo "<td>";
echo "<input type=\"checkbox\" name=\"food_cat[]\" value=$food checked>$food</input>";
echo "</td>";
}
else{
echo "<td>";
echo "<input type=\"checkbox\" name=\"food_cat[]\" value=$food>$food</input>";
echo "</td>";
}
}

?>

</tr>
<tr>

<td colspan="6" style="padding-left:30em">
<input type="submit" name="submit" value="save">
</td>
</table>
</form>
</body>
</html>

Whenever you execute above php code output like below will be displayed in the browser.










What is your favorite food?
fishmeatvegetablefastfoodsoup





Related Documents
http://arjudba.blogspot.com/2009/07/entering-mutiple-values-with-checkbox.html

Entering multiple values with checkbox into mysql

In this post I will discuss how I can pass multiple values of checkbox into mysql database. If we try to insert checkbox data in normal way then we will see only one value of it is inserted. Also, there is exactly one field to hold multiple checkboxes data unless you want to insert multiple records into database. Now the question is how to insert multiple values into one field for checkbox data.

There are several ways by which we can insert multiple checkbox data into mysql database. In the following section it is discussed.

Way 01 Using Implode function
1)Prepare table to hold multiple checkbox data.
Declare as varchar of the field that will hold checkbox data. Note that your database field must be greater than the summation of all checkbox values length so that it can hold multiple checkbox value.

mysql> create table checkbox(foods varchar(60));
Query OK, 0 rows affected (0.14 sec)

mysql> select * from checkbox;
Empty set (0.00 sec)

2)Note that to insert multiple checkbox values, all checkbox html name must be declared as array. Like in this example it is declared as,
-<input type="checkbox" name="all_food[]" value=$food>$food</input>

And while inserting value into database we need to append a character like comma(,) after each checkbox value so that we can distinguish multiple checkboxes data. This is done by implode function as in described in the example.

<?
if(isset($_POST['submit'])) {
include('include/db.php');
$arrays = implode(",",$_POST['all_food']);
$query="insert into checkbox values('".$arrays."')";
//echo $query;
mysql_query($query) or die ('Error inserting values into database, please go back and try again');
mysql_close();
}
?>

<html>
<body>
<form method="post">
<table width="50%">
<th>What is your favorite food?</th>
<tr>
<?
$array_food=array('fish','meat','vegetable','fastfood','soup');
foreach($array_food as $food){
echo "<td>";
echo "<input type=\"checkbox\" name=\"all_food[]\" id=\"all_food\" value=$food>$food</input>";
echo "</td>";
}

?>

</tr>
<tr>

<td colspan="6" style="padding-left:30em">
<input type="submit" name="submit" value="save">
</td>
</table>
</form>
</body>
</html>

If we run above php code and after check different checkboxes multiple values are inserted into database as below.

mysql> select * from checkbox;
+--------------------------+
| foods |
+--------------------------+
| meat,vegetable,fast,soup |
| meat,vegetable,fastfood |
| fish,meat,fastfood |
+--------------------------+
3 rows in set (0.00 sec)

Way 02: Inserting data using serialize function

<?
if(isset($_POST['submit'])) {
include('include/db.php');
$arrays = serialize($_POST['all_food']);
$query="insert into checkbox values('".$arrays."')";
//echo $query;
mysql_query($query) or die (mysql_error());
mysql_close();
}
?>

<html>
<body>
<form method="post">
<table width="50%">
<th>What is your favorite food?</th>
<tr>
<?
$array_food=array('fish','meat','vegetable','fastfood','soup');
foreach($array_food as $food){
echo "<td>";
echo "<input type=\"checkbox\" name=\"all_food[]\" value=$food>$food</input>";
echo "</td>";
}

?>

</tr>
<tr>

<td colspan="6" style="padding-left:30em">
<input type="submit" name="submit" value="save">
</td>
</table>
</form>
</body>
</html>


From the database it will display,

mysql> select * from checkbox;
+--------------------------------------------------------------+
| foods |
+--------------------------------------------------------------+
| a:3:{i:0;s:4:"meat";i:1;s:9:"vegetable";i:2;s:8:"fastfood";} |
| a:3:{i:0;s:4:"fish";i:1;s:4:"meat";i:2;s:8:"fastfood";} |
| a:2:{i:0;s:4:"meat";i:1;s:4:"soup";} |
+--------------------------------------------------------------+
3 rows in set (0.00 sec)


Here,
- a:3 indicates how many checkbox values are there.
- i:0 indicates it is the first checkbox value inserted. i:1 means it is in the serial second to be inserted data into mysql database and so on.
- s:4 indicates how many letters in the value. s:4 means four letters, s:8 means eight letters.

Related Documents
Datatypes in Php
Integer and floating point number in Php
Variables in PHP

Tuesday, July 21, 2009

How to include a php file inside smarty template

Well, many one of you heard about smarty template. In simple way we can say, Smarty template makes your PHP scripts independent of the layout.

While working with smarty template you may need to run a php code from the smarty template. Smarty always give the flexibility to do display code simply as a text as well as to execute php code.

Let's assume we have just installed smarty.
-You will see under Smarty>libs folder the main smarty class php file named Smarty.class.php and we need to make instance of Smarty class to use it.

-You can see sample code under Smarty>demo.

-And the template resides under Smarty>demo>templates.

Now we will execute php script named welcome.php from template named welcome.tpl

My welcome.php contains,
<?php
echo "Welcome to arjudba world.";
?>


and is saved under Smarty>demo.

My welcome.tpl contains,
{include_php file="welcome.php"}

and is saved under Smarty>demo>temaplates. Note that we can give full path here. Like {include file="include($_SERVER['DOCUMENT_ROOT'].'/includes/welcome.php');"}

Now from a php file we need to call the template file welcome.tpl and eventually template file will call welcome.php file. Let's name this php file as Smarty/display.php which contains,

<?php

require '../libs/Smarty.class.php';

$smarty = new Smarty;

$smarty->compile_check = true;
$smarty->debugging = true;
$smarty->display('welcome.tpl');

?>



Now in browser if you run for example on machine http://localhost/smarty/demo/display.php it will display,
Welcome to arjudba world.

And you are done. From welcome.tpl you ran welcome.php script.

I have shown a simple way above about how to run php script from template. There are other ways to do the job. Like in the template file writing as,

{php}
include("welcome.php");
{/php}


Related Documents
Datatypes in Php
Integer and floating point number in Php
Variables in PHP
Magic constants in php
Boolean datatype in Php

Tuesday, June 23, 2009

How to see directory contents, file size, file type, modification date using php

There is already some raw output of directory contents which is shown in the post List of directory contents using array in php. In this post I will display the directory contents into more readable format as well as the contents size, file type and modification date of the file/folder.

We will start by making a hard code directory in our code to which contents file type, size will be displayed.

1)We assign the directory location to a path so that we can work further with this $path variable.
$path='D:/test';

2)You need to open the directory using php opendir() function.
$myDirectory = opendir($path);

3)Using a while loop read each directory contents and put them into an array variable named $dirArray.
while($entryName = readdir($myDirectory)) {
$dirArray[] = $entryName;
}

4)As we already read all the contents and the contents are within array variable so now we can close the directory using,
closedir($myDirectory);

5)We need to count the number of elements inside the array, in order words number of files exist inside the operating system directory.
$indexCount = count($dirArray);

6)Optionally we are sorting here so that we can display them in an order.
sort($dirArray);

7)As you have seen in the example http://arjudba.blogspot.com/2009/03/list-of-directory-contents-using-array.html [0] => . [1] => .. are there and you might not want to display those hidden contents. So before displaying contents you will check whether filename starts with a dot (.) . If it starts with a dot file will not be displayed on the browser. Simply using if condition we can omit it.
if (substr("$dirArray[$i]", 0, 1) != ".")

8)To display all files in the array we can use for loop construct.
for($i=0; $i < $indexCount; $i++) Now the above php lines are combined and embedded with html in order to display result in a good format. Full code is below.

<?
$path='D:/test';
// open this directory
$myDirectory = opendir($path);

// get each entry
while($entryName = readdir($myDirectory)) {
$dirArray[] = $entryName;
}

// close directory
closedir($myDirectory);

// count elements in array
$indexCount = count($dirArray);

// sort them
sort($dirArray);
?>

<html>
<body>
<table style="margin-bottom: 1px;" border="0" cellpadding="6" cellspacing="1" width="90%">
<tbody>
<tr>
<th class="TableData" style="padding-left: 11px; padding-right: 1px;"
bgcolor="#dadce1" width="300" height="22">File Name
</th>

<th class="TableData" style="padding-left: 11px; padding-right: 1px;"
bgcolor="#dadce1" width="100" height="22">File Size
</th>

<th class="TableData" style="padding-left: 11px; padding-right: 1px;"
bgcolor="#dadce1" width="350" height="22">Date Modified
</th>

<th class="TableData" style="padding-left: 11px; padding-right: 1px;"
bgcolor="#dadce1" width="110" height="22">File Type
</th>

<?
for($i=0; $i < $indexCount; $i++) {
// don't list hidden files
if (substr("$dirArray[$i]", 0, 1) != "."){

?>

<tr>
<td class="Lebels" align="right" bgcolor="#e9ece9" >
<? echo $dirArray[$i]; ?>
</td>
<?
print("<td bgcolor=\"#e9ece9\">");
# We may want a file size. Note that you need to add path
if( filesize( $path . "/" . $dirArray[$i] ) >= 1024 ) {
# Size in kilobytes
print " " . round( filesize( $path . "/" . $dirArray[$i] ) / 1024, 1 )
. " K<br />\n";
} elseif( filesize( $path . "/" . $dirArray[$i] ) >= 1048576 ) {
# Size in megabytes
print " " . round( filesize( $path . "/" . $dirArray[$i] ) / 1024 / 1024, 1 ) . " M<br />\n";
} else {
# Size in bytes
print " " . filesize( $path . "/" . $dirArray[$i] ) . " bytes<br />\n";
}
print("</td>");
?>

<td class="Values" bgcolor="#e9ece9" ><? echo date ("F d Y H:i:s.", filemtime($path . "/" . $dirArray[$i])); ?>
</td>

<td class="Values" bgcolor="#e9ece9" >
<? print(filetype($path . "/" . $dirArray[$i] ));?>

</td>
</tr>
<?
}
}

print("</TABLE>\n");
?>
</body>
</html>

A sample output in my system of the above output is,
File Name File Size Date Modified File Type
Accounts.txt 297 bytes
December 21 2008 16:26:39. file
Ghor_Kutum_16.wmv 23232.6 K
February 08 2009 11:12:36. file
New Folder 0 bytes
June 23 2009 14:58:47. dir
SPFILEORCL.ORA 3.5 K
May 16 2009 06:26:53. file
a.txt 51 bytes
May 16 2009 06:16:28. file
database_dump.txt 10.9 K
June 19 2009 11:09:30. file
database_testprotege_profile.csv 1.7 K
June 20 2009 16:50:32. file
zwt-escep310.rar 1089.7 K
December 13 2008 08:38:16. file


Related Documents

Thursday, June 18, 2009

Warning: Cannot modify header information -headers already sent

Problem Description
Whenever you run a php file in the browser it shows the following warning message.
Warning: Cannot modify header information - headers already sent by (output started at E:\xampp\htdocs\mock9\pro01.php:86) in E:\xampp\htdocs\mock9\pro01.php on line 168

A variant of above error is after Warning message a function name is appended and then a error message before displaying "headers already sent".
Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at E:\xampp\htdocs\mock9\index.php:4) in E:\xampp\htdocs\mock9\index.php on line 9

Cause and Problem of the Problem
This error "headers already sent" indicates that there are spaces, new lines, other garbage words or in fact any words before an opening tag <?php or after the ending tag ?>.

This same error also occur in fact case 1) if you display any output before sending any header information. Like if you display output like,
echo $query;

before sending header information like before line,
header ("location: pro02.php?pid=$pro_id");
then above error will appear.

It is important to note that with the error message
output started at E:\xampp\htdocs\mock9\pro01.php:86) in E:\xampp\htdocs\mock9\pro01.php on line 168
- It mean that the problem is inside E:\xampp\htdocs\mock9\pro01.php
- The line number that cause the problem is 86 not 168.

Similarly by error message,
output started at E:\xampp\htdocs\mock9\index.php:4) in E:\xampp\htdocs\mock9\index.php on line 9
indicates that,
- Victim file is E:\xampp\htdocs\mock9\index.php
- The problem is in line number 4.

Solution of the Problem

Sunday, June 14, 2009

How to edit data of Mysql using php

You have already familiar with the how to access mysql database as well as how to insert data into mysql database. How to access mysql database topic is discussed on http://arjudba.blogspot.com/2009/06/how-to-access-mysql-database-using-php.html and how to insert data into mysql database is discussed on http://arjudba.blogspot.com/2009/06/how-to-insert-data-into-mysql-database.html.

Using the insert php code which is discussed in the above link we have inserted 3 rows into basic_info table of the mysql database. Querying basic_info from mysql database yields following result,

mysql> select * from basic_info;
+---------------------------+------+----------------+
| name | age | phone |
+---------------------------+------+----------------+
| Mohammad Abdul Kasem | 65 | 01734060483 |
| Fariha Tasnuva Queen | 23 | +01912046954 |
| Mohammad Abdul Momin Arju | 23 | +8801710282272 |
+---------------------------+------+----------------+
3 rows in set (0.00 sec)

Now using php code we like to update the row based on phone number. At first in the browser it will ask phone number and then corresponding row will be displayed where user will edit information and then submit. In the mysql database that row will be updated.

Step by step whole process is discussed.

1)Create form which will take phone number from user.
The following code will create a form which will create a form that will take phone number from user and also it contains a submit button.


<html>
<body>
<form method="post">
<table style="margin-bottom: 1px; padding-left:10px;" border="0" cellpadding="0"
cellspacing="1" width="75%">
<tbody>
<tr>
<td align="right" bgcolor="#e9ece9" >Enter Phone no. to edit: </td>
<td bgcolor="#e9ece9" style="padding-left:4px;" >
<input name="phone" size="20" maxlength="20" value="<? echo $phone; ?>">
</td>
</tr>
</tbody>
</table>


<table style="margin-bottom: 1px; padding-left:455px;" border="0" cellpadding="0" cellspacing="1" width="50%">
<tbody>
<tr>
<td colspan="2" align="right" bgcolor="#dadce1" height="4">
<input name="submit" value="submit" type="submit">
</td>
</tr>
</tbody>
</table>

</body>
</html>

2)Display data from the database based on corresponding phone number.
We need php code to display data based on the phone number he typed on to browser. Below is the simple piece of code and you will understand easily the code if you have gone through my previous two posts.
It is displayed a submit button which in fact will update data into database.

<?php
#Form Variables.
$phone='';

#Database connection strings.
$ip='localhost';
$mysqluser='root';
$mysqlpass='test';
$mysqldb='test';

if(isset($_POST['submit'])){
extract($_POST);

#Build connection to mysql server.
$link= mysql_connect($ip, $mysqlUser, $mysqlPass)
or die('Could not connect: ' . mysql_error());

#Select a database to which we will perform operation.
mysql_select_db($mysqldb) or die('Could not select database');

#A query is written which will extract all information
#from basic_info table based on phone number entered.

$query = "SELECT * FROM basic_info where phone='".$phone."'";
#Execute query and store result into variable $result.
#echo $query;
$result = mysql_query($query) or die('Query failed: ' . mysql_error());

while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
$name=$row["name"];
$age=$row["age"];
$phone=$row["phone"];
}

echo "<form method=\"post\">";
echo "<table style=\"margin-bottom: 1px;\" border=\"0\" cellpadding=\"0\" cellspacing=\"1\" width=\"60%\">\n";
echo "\t<tr>\n";
echo "\t\t<td bgcolor=\"#dadce1\" colspan=\"2\">Information of Phone:\t $phone</td>";
echo "\t\t<td bgcolor=\"#dadce1\"> <input type=\"hidden\" value='$phone' name=\"phone\" size=\"50\" ></td>";

echo "\t</tr>\n";

echo "\t<tr>\n";
echo "\t\t<td bgcolor=\"#dadce1\">Name:</td>";
echo "\t\t<td bgcolor=\"#dadce1\"> <input type=\"text\" value='$name' name=\"name\" size=\"50\" ></td>";
echo "\t</tr>\n";

echo "\t<tr>\n";
echo "\t\t<td bgcolor=\"#dadce1\">Age:</td>";
echo "\t\t<td bgcolor=\"#dadce1\"> <input type=\"text\" value='$age' name=\"age\" size=\"2\"></td>";
echo "\t</tr>\n";

echo "</table>\n";

echo "<table style=\"margin-bottom: 1px;\" border=\"0\" cellpadding=\"0\" cellspacing=\"1\" width=\"40%\">";
echo "<tr>";
echo "<td colspan=\"2\" align=\"right\" bgcolor=\"#dadce1\" height=\"4\">";
echo "<input name=\"submit02\" value=\"submit\" type=\"submit\">";
echo "</td>";
echo "</tr>";
echo "</table>";
echo "</form>";
#Free up Memory for $result.

mysql_free_result($result);
#Close database connection.
mysql_close($link);
}
?>

3)Update data into database upon pressing submit button:
Here also we need to write php code to update data into database. With a hidden field
phone number is passed to another form and using phone number data is updated in the database.
Below is the php code that will handle the update.

<?php
#Form Variables.
$phone='';
$name='';
$age='';

#Database connection strings.
$ip='localhost';
$mysqluser='root';
$mysqlpass='test';
$mysqldb='test';

if(isset($_POST['submit02'])){
$phone=$_POST["phone"];
$age=$_POST["age"];
$name=$_POST["name"];

#Build connection to mysql server.
$link= mysql_connect($ip, $mysqlUser, $mysqlPass)
or die('Could not connect: ' . mysql_error());

#Select a database to which we will perform operation.
mysql_select_db($mysqldb) or die('Could not select database');

#A query is written which will extract all information
#from basic_info table based on phone number entered.

$query = "update basic_info
set name='".$name."',
age='".$age."'
where
phone='".$phone."'";
#echo $query;
#Execute query and store result into variable $result.
#echo $query;
mysql_query($query) or die('Query failed: ' . mysql_error());
echo "Update Successfully done";
#Close database connection.
mysql_close($link);
}
?>

4)Run the code.
Total code is look like,

<?php
#Form Variables.
$name='';
$age='';
$phone='';

#Database connection strings.
$ip='localhost';
$mysqluser='root';
$mysqlpass='test';
$mysqldb='test';

if(isset($_POST['submit'])){
extract($_POST);

#Build connection to mysql server.
$link= mysql_connect($ip, $mysqlUser, $mysqlPass)
or die('Could not connect: ' . mysql_error());

#Select a database to which we will perform operation.
mysql_select_db($mysqldb) or die('Could not select database');

#Build query that will insert values into database
$query="insert into basic_info(name, age, phone) values('".$name."','".$age."','".$phone."')";

#Execute query
mysql_query($query) or die ("Error Inserting values into database");

#Close database connection.
mysql_close($link);

}
?>

<html>
<body>
<form method="post">
<table style="margin-bottom: 1px; padding-left:10px;" border="0" cellpadding="0"
cellspacing="1" width="75%">
<tbody>
<tr>
<td align="right" bgcolor="#e9ece9" >Name: </td>
<td bgcolor="#e9ece9" style="padding-left:4px;">
<input name="name" size="50" maxlength="50" width="50" value="<? echo $name; ?>">
</td>
</tr>

<tr>
<td align="right" bgcolor="#e9ece9" >Age: </td>
<td bgcolor="#e9ece9" style="padding-left:4px;">
<input name="age" size="2" maxlength="2" width="2" value="<? echo $age; ?>">
</td>
</tr>

<tr>
<td align="right" bgcolor="#e9ece9" >Phone: </td>
<td bgcolor="#e9ece9" style="padding-left:4px;" >
<input name="phone" size="20" maxlength="20" value="<? echo $phone; ?>">
</td>
</tr>
</tbody>
</table>

<table style="margin-bottom: 1px;" border="0" cellpadding="0" cellspacing="1" width="40%">
<tbody>
<tr>
<td colspan="2" align="right" bgcolor="#dadce1" height="4">
<input name="submit" value="submit" type="submit">
</td>
</tr>
</tbody>
</table>
</form>
</body>
</html>

Now save it into a file and load into browser.

It will be displayed as after submitting phone number +8801710282272,
Enter Phone no. to edit:
Information of Phone: +8801710282272
Name:
Age:


Edit name and/or age field in the browser and press submit button.

Now I changed it to,
Enter Phone no. to edit:
Information of Phone: +8801710282272
Name:
Age:


After pressing submit button it shows,
Update Successfully done

and now from database I issue query and it shows.

mysql> select * from basic_info;
+----------------------+------+----------------+
| name | age | phone |
+----------------------+------+----------------+
| Mohammad Abdul Kasem | 65 | 01734060483 |
| Fariha Tasnuva Queen | 23 | +01912046954 |
| Arju | 24 | +8801710282272 |
+----------------------+------+----------------+
3 rows in set (0.00 sec)

And row is updated.

In fact you can do same query and display output in your browser with the help of post,
http://arjudba.blogspot.com/2009/06/how-to-access-mysql-database-using-php.html
Related Documents
http://arjudba.blogspot.com/2009/06/how-to-access-mysql-database-using-php.html
http://arjudba.blogspot.com/2009/06/how-to-insert-data-into-mysql-database.html

How to insert data into mysql database using php

How to access or read data from mysql database table using php is discussed in the topic http://arjudba.blogspot.com/2009/06/how-to-access-mysql-database-using-php.html. In this post I will discuss how to insert or write data into mysql database using php.

To do that, I will use a form and user will fill out the form and upon pressing submit button the data will be inserted into mysql database. So before inserting data into mysql database we need to setup database- that means we have the database table with appropriate fields.

1)Setup Database.

Let's create a database table named basic_info for mysql test database.
D:\xampp\mysql\bin>mysql -u root -ptest
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.1.30-community MySQL Community Server (GPL)

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql> use test;
Database changed

mysql> create table basic_info(
-> name varchar(50),
-> age int(2),
-> phone varchar(20));
Query OK, 0 rows affected (0.22 sec)

mysql> select * from basic_info;
Empty set (0.06 sec)

2)Create a simple html form.
Below is my form which will display Name, age, phone field in the browser and a simple submit button.

<html>
<body>
<form method="post">
<table style="margin-bottom: 1px; padding-left:10px;" border="0" cellpadding="0"
cellspacing="1" width="75%">
<tbody>
<tr>
<td align="right" bgcolor="#e9ece9" >Name: </td>
<td bgcolor="#e9ece9" style="padding-left:4px;">
<input name="name" size="50" maxlength="50" width="50" value="<? echo $name; ?>">
</td>
</tr>

<tr>
<td align="right" bgcolor="#e9ece9" >Age: </td>
<td bgcolor="#e9ece9" style="padding-left:4px;">
<input name="age" size="2" maxlength="2" width="2" value="<? echo $age; ?>">
</td>
</tr>

<tr>
<td align="right" bgcolor="#e9ece9" >Phone: </td>
<td bgcolor="#e9ece9" style="padding-left:4px;" >
<input name="phone" size="20" maxlength="20" value="<? echo $phone; ?>">
</td>
</tr>
</tbody>
</table>

<table style="margin-bottom: 1px;" border="0" cellpadding="0" cellspacing="1" width="40%">
<tbody>
<tr>
<td colspan="2" align="right" bgcolor="#dadce1" height="4">
<input name="submit" value="submit" type="submit">
</td>
</tr>
</tbody>
</table>
</form>
</body>
</html>

3)Prepare php code that will insert data into database submitted into browser.

<?php
#Form Variables.
$name='';
$age='';
$phone='';

#Database connection strings.
$ip='localhost';
$mysqluser='root';
$mysqlpass='test';
$mysqldb='test';

if(isset($_POST['submit'])){
extract($_POST);

#Build connection to mysql server.
$link= mysql_connect($ip, $mysqlUser, $mysqlPass)
or die('Could not connect: ' . mysql_error());

#Select a database to which we will perform operation.
mysql_select_db($mysqldb) or die('Could not select database');

#Build query that will insert values into database
$query="insert into basic_info(name, age, phone) values('".$name."','".$age."','".$phone."')";

#Execute query
mysql_query($query) or die ("Error Inserting values into database");
}
?>

4)Combine php code with html form.

<?php
#Form Variables.
$name='';
$age='';
$phone='';

#Database connection strings.
$ip='localhost';
$mysqluser='root';
$mysqlpass='test';
$mysqldb='test';

if(isset($_POST['submit'])){
extract($_POST);

#Build connection to mysql server.
$link= mysql_connect($ip, $mysqlUser, $mysqlPass)
or die('Could not connect: ' . mysql_error());

#Select a database to which we will perform operation.
mysql_select_db($mysqldb) or die('Could not select database');

#Build query that will insert values into database
$query="insert into basic_info(name, age, phone) values('".$name."','".$age."','".$phone."')";

#Execute query
mysql_query($query) or die ("Error Inserting values into database");
}
?>

<html>
<body>
<form method="post">
<table style="margin-bottom: 1px; padding-left:10px;" border="0" cellpadding="0"
cellspacing="1" width="75%">
<tbody>
<tr>
<td align="right" bgcolor="#e9ece9" >Name: </td>
<td bgcolor="#e9ece9" style="padding-left:4px;">
<input name="name" size="50" maxlength="50" width="50" value="<? echo $name; ?>">
</td>
</tr>

<tr>
<td align="right" bgcolor="#e9ece9" >Age: </td>
<td bgcolor="#e9ece9" style="padding-left:4px;">
<input name="age" size="2" maxlength="2" width="2" value="<? echo $age; ?>">
</td>
</tr>

<tr>
<td align="right" bgcolor="#e9ece9" >Phone: </td>
<td bgcolor="#e9ece9" style="padding-left:4px;" >
<input name="phone" size="20" maxlength="20" value="<? echo $phone; ?>">
</td>
</tr>
</tbody>
</table>

<table style="margin-bottom: 1px;" border="0" cellpadding="0" cellspacing="1" width="40%">
<tbody>
<tr>
<td colspan="2" align="right" bgcolor="#dadce1" height="4">
<input name="submit" value="submit" type="submit">
</td>
</tr>
</tbody>
</table>
</form>
</body>
</html>

5)Run above code and fill fields and press submit button.
After running above code it will display following in your browser. Then I filled it like below.

Name:
Age:
Phone:


6)Query from database and be sure data is inserted.

mysql> select * from basic_info;
+---------------------------+------+----------------+
| name | age | phone |
+---------------------------+------+----------------+
| Mohammad Abdul Momin Arju | 23 | +8801710282272 |
+---------------------------+------+----------------+
1 row in set (0.03 sec)


Related Documents

How to access Mysql database using php

It is quite easy task to access mysql database using php. The detail procedure is discussed step by step.

1)Establish Connection to Mysql:
The first thing is need to establish connection to Mysql database. With the mysql_connect() function a connection is opened to Mysql server. The syntax to use mysql_connect() function is,

$link=mysql_connect('mysql_host:port', 'mysql_user', 'mysql_password')
or die('Could not connect: ' . mysql_error());


where,
mysql_connect – is a built in function to connect to a database.

mysql_host – tells the server to connect which host. May be a localhost or remote host. You can provide IP address of the server too. The default host is localhost.

port - tells the server to connect through which port. The default port is 3306.

mysql_user – this is the username for the database to connect. Default value is defined by mysql.default_user. In SQL safe mode, this parameter is ignored and the name of the user that owns the server process is used.

mysql_password – This is the mysql user password. Default value is defined by mysql.default_password. In SQL safe mode, this parameter is ignored and empty password is used.

Or die – It will return an error if we cannot connect to the database.

mysql_error - It is another mysql built in function which will return the text of the error message from previous MySQL operation. So if mysql_connect is unsuccessful mysql_error will be populated with error messages.

2)Select mysql database:
The second step is to select a database. As in the mysql server there may be many databases but we need to specify on which database we will do operation. With mysql_select_db built in function a mysql database is selected.

The usage syntax is,
mysql_select_db('my_database') or die('Could not select database');
where,
my_database - is the name of the mysql database to use.

or die - If it can't select the database it's portion will be executed.

3)Perform SQL query to access database.
Now that we have a connection to the database, we will need to build our query. We will be selecting user, password field from user table of mysql database.

So our query will look like,
$query = 'SELECT USER, PASSWORD FROM user';

Note that the query string should not end with a semicolon.

Now in order to send this query to mysql database and store the result into variable $result issue,
$result = mysql_query($query) or die('Query failed: ' . mysql_error());

4)Display results in the browser.
We have the results of the query inside variable $result. So we need to display it into browser.

With built in function mysql_fetch_array() we can fetch a result row as an array and moves the internal data pointer ahead. We can use the following code to display result as html.

echo "<table>\n";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";


5)Free result memory:
Our task is now completed and hence we need to free up memory that is occupied by $result. By calling mysql_free_result() function we can free all memory associated with the $result. The syntax of calling the function is,

mysql_free_result($result);

6)Close Mysql database connection:
The mysql_close() closes the non-persistent connection to the MySQL server that's associated with the specified link identifier.
The syntax of closing database connection is,
mysql_close($link);

Here is our final code.

<?php

#Mysql database username is root and password is test

$link=mysql_connect('localhost', 'root', 'test')
or die('Could not connect: ' . mysql_error());

#We are selecting mysql database itself for query.
mysql_select_db('mysql') or die('Could not select database');

#A query is written to select username and password from table user.
$query = 'SELECT USER, PASSWORD FROM user';

#Execute query and store result into variable $result.
$result = mysql_query($query) or die('Query failed: ' . mysql_error());

#Html table to display result well.
echo "<table style=\"margin-bottom: 1px;\" border=\"0\" cellpadding=\"0\" cellspacing=\"1\" width=\"100%\">\n";

#While loop to fetch row one by one.
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td bgcolor=\"#dadce1\">$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";

#Free up Memory for $result.
mysql_free_result($result);

#Close database connection.
mysql_close($link);
?>

And output displayed on the screen is,
root*94BDCEBE19083CE2A1F959FD02F964C7AF4CFC29
root
pma
magento*38EFCD3985CA39B52BDBC1C002C4DF9CB86BB039
magento*38EFCD3985CA39B52BDBC1C002C4DF9CB86BB039
momin*7CEB3FDE5F7A9C4CE5FBE610D7D8EDA62EBE5F4E
robert*94BDCEBE19083CE2A1F959FD02F964C7AF4CFC29
richard*94BDCEBE19083CE2A1F959FD02F964C7AF4CFC29
rober4t*94BDCEBE19083CE2A1F959FD02F964C7AF4CFC29


Related Documents
http://arjudba.blogspot.com/2009/05/creating-and-using-database-in-mysql.html
http://arjudba.blogspot.com/2009/05/connecting-to-and-disconnecting-from.html
http://arjudba.blogspot.com/2009/05/create-user-in-mysql.html

Sunday, April 19, 2009

Magneto installation crashes Apache HTTP Server

Problem Description
I downloaded magneto 1.3.1 and whenever I tried to installed on xampp version 2.5. After agree their terms I provided time, currency and language. Then in the next windows hostname, database name, password but after waiting a long time apache crashed with message "Apache HTTP Server has encountered a problem and needs to close. We are sorry for the inconvenience" And a dialog box came with title "apache.exe - Application Error" saying "The instruction at "%s" referenced memory at "0x00000000". The memory could not "read". The two figures are shown below.
















Cause of the problem
Before xampp 1.7.0 magneto installation worked perfect. But after xampp 1.7.0 magneto installation crashes apache. The reason is after xampp 1.7.0 php uses PDO and any php programs using PDO crashed apache. That's why whenever you install magneto with XAMPP 1.6.8 it would work perfect.

Solution of the Problem
From the link http://windows.php.net/downloads/snaps/php-5.2-win32-VC6-x86-latest.zip download php or download some higher version of php, then unzip, and finally copy libmysql.dll into xampp\apache\bin

After that restart your apache server and try to install magneto. It should work perfect.

If still you get error then check whether another instance of php that would have caused your issue or at least another php.ini file in the Windows folder perhaps and/or a path variable pointing to your other instance of php in the Environmental Variables or this points to "path" System Environment Variable or in a registry. In that removing those entry will fix the problem.

Related Documents
http://arjudba.blogspot.com/2009/04/installing-magneto-fails-with-php.html
http://arjudba.blogspot.com/2009/04/after-installing-magento-cant-log-in-to.html

Installing magneto fails with PHP Extension "curl" must be loaded

Problem Description
While install magneto it fails with message,
PHP Extension "curl" must be loaded

Cause of the problem
After the Magento release (0.6.12510) installation wizard, it is checked whether php_curl.dll extension is enabled inside php.ini file. If the extension is disabled then magneto installation fails with above message.

Solution of the problem
On your windows machine with XAMPP installed go to the apache/bin/ directory.

There you will find php.ini file. Open the file with any editing software (like notepad). Search for (CTRL+F) for curl. You will find a line like below.
;extension=php_curl.dll
which means it is commented. Comment out it i.e remove semicolon (;). In order word make it like below.
extension=php_curl.dll
and save the file.

After save it restart you apache web server.

And then try to install the magneto. You will see it is successful.

If you use debian linux or ubuntu then you can fix the problem by,
apt-get install php5-curl
Related Documents
http://arjudba.blogspot.com/2009/04/magneto-installation-crashes-apache.html

Wednesday, April 1, 2009

Object interface example in php

Think about your laptop or computer, you did not interact with the things that is inside within it. To on your machine you press the power button. Similarly you interact with your machine through mouse, keyboard etc. The methods through which you interact with the object togetherly forms an interface.

You can define an interface in this way. An interface is the group of related methods without bodies. Details implementation of the interface will be within classes that implements the interface.

Note that, all methods in the interface must be public as by it's nature and if a class implements an interface all the methods must be defined within the class. Interface methods does not tell how it will work that is details implementation of interface methods must be handle within the class that implements the interface; how that class will use the method.

You can't create instance of an interface. Interface can be subclassed.

To create an interface you have to use interface keyword followed by the curly brace. Methods declaration will be inside the curly brace. To implements an interface you have to use implements keyword with the class definition that will implement the interface.

Below is an example of using interface.

<?php
interface a{
public function method1();
}
interface b{
public function method2();
}
interface c extends a,b{
public function method3($name);
}
class d implements c{
public function method1(){
}
public function method2(){
}
public function method3($name){
}
}

?>

Related Documents
http://arjudba.blogspot.com/2009/03/abstract-class-and-abstract-method-with.html
http://arjudba.blogspot.com/2009/03/static-declaration-with-example-in-php.html
http://arjudba.blogspot.com/2009/03/class-concepts-and-usage-syntax-in-php.html
http://arjudba.blogspot.com/2009/03/class-inheritance-example-in-php.html
http://arjudba.blogspot.com/2009/03/autoloading-objects-in-php.html
http://arjudba.blogspot.com/2009/03/constructors-and-destructors-in-php.html

Tuesday, March 31, 2009

Abstract class and abstract method with example in php

In php, you can define a class as abstract class. In fact if you want to keep any method of a class as abstract that class must be declared as abstract class. So, there is both abstract classes and abstract methods.

A class defined as abstract class can't be instantiated, which means we can't create instance of that class but it can be subclassed. If methods are declared as abstract then they can't conatin implementation, that means without any braces and followed by semicolon(;) like,
abstract protected function display();

Abstract class may or may not include abstract methods.

When a subclass is inherited from abstract class all methods marked as abstract class declaration in the parent must be defined in the subclass.

The scope of the derived class method must be less restrictive than the scope of the base class method if it is declared as abstract method. For example, if base class abstract method is declared as protected then within derived class method or in other word the function implementation must be defined as either protected or public, but not private.

Below is an example of abstract class and abstract method in php,

<?php
abstract class AbstractClass{
//Only abstract class declartion here. Implementation must be inside subclass
abstract protected function abstractTest1();
abstract protected function abstractTest2($suffix);
public function display(){
echo $this->abstractTest1();
}
}

class SubClass1 extends AbstractClass{
protected function abstractTest1(){
return "SubClass1";
}
public function abstractTest2($suffix){
return "SubClass1 ".$suffix;
}
}
class SubClass2 extends AbstractClass{
public function abstractTest1(){
return "SubClass2";
}
public function abstractTest2($suffix){
return "SubClass2 ".$suffix;
}
}

$subclass1Instance=new SubClass1();
$subclass1Instance->display(); //Protected method can be called here.
echo "<br />";
echo $subclass1Instance->abstractTest2("Class1");
echo "<br />";
$subclass2Instance=new SubClass2();
echo $subclass2Instance->abstractTest1(); //As we declared public so can be access here.
echo "<br />";
echo $subclass2Instance->abstractTest2("Class2");

?>

An the output is,

SubClass1
SubClass1 Class1
SubClass2
SubClass2 Class2

Related Documents
http://arjudba.blogspot.com/2009/03/static-declaration-with-example-in-php.html
http://arjudba.blogspot.com/2009/03/class-concepts-and-usage-syntax-in-php.html
http://arjudba.blogspot.com/2009/03/class-inheritance-example-in-php.html
http://arjudba.blogspot.com/2009/03/autoloading-objects-in-php.html
http://arjudba.blogspot.com/2009/03/constructors-and-destructors-in-php.html

Static declaration with example in php

In php, you can declare method or member of a class as static. If you do so then you can access the method/member without creating any instance.

In fact, if you declare a member of a class as static then that member can't be accessed with an instantiated class object. So you would not be able to access a static variable using arrow sign. However static method can be accessed via instantiation.

Another thing about static method is, the pseudo variable $this is not available inside the method declared as static.

Below is an example of static declaration with example in php.

<?php
class StaticExample{
static $staticVariable=10;
static function staticMethod(){
echo "This method is declared as static";
}
}
echo StaticExample::$staticVariable;
echo "<br />";
StaticExample::staticMethod();
echo "<br />";
$staticExampleInstance=new StaticExample();
$staticExampleInstance->staticMethod();
echo "<br />";
echo $staticExampleInstance->staticVariable; //This is undefined, so no output will be displayed.
?>

And in browser the output is,

10
This method is declared as static
This method is declared as static

Related Documents
http://arjudba.blogspot.com/2009/03/class-concepts-and-usage-syntax-in-php.html
http://arjudba.blogspot.com/2009/03/class-inheritance-example-in-php.html
http://arjudba.blogspot.com/2009/03/autoloading-objects-in-php.html
http://arjudba.blogspot.com/2009/03/constructors-and-destructors-in-php.html

Monday, March 30, 2009

Public, protected and private scope in php

Prepend the public or private or protected keyword before a variable declaration define the scope of the variable.

If the variable is declared as public then that variable can be accessed from anywhere.

If the variable is declared as proteced then that variable can be accessed from parent class and inherited classes and the class that define the variable.

If variable is declared as private then it is only available within the class that defines it.

If neither public/private/protected keyword are specified in declaration then by default the method/variable becomes public.

Below is an example with these keywords.

<?php
class BaseClass{
public $publicVar='Public Variable ';
protected $protectedVar='Protected Variable ';
private $privateVar='Private Variable';

public function display(){
echo $this->publicVar;
echo $this->protectedVar;
echo $this->privateVar;
}
}

class DerivedClass extends BaseClass{
protected $protectedVar2='Protected Variable 2';


function display(){
echo $this->publicVar;
echo $this->protectedVar;
echo $this->protectedVar2;
echo $this->privateVar;
}
}
$baseInstance=new BaseClass();
echo $baseInstance->publicVar; //It will work as public
echo "<br />";
//echo $baseInstance->protectedVar; //Fatal error as protected can be accessed within base and derived class.
//echo "<br />";
//echo $baseInstance->privateVar; //Fatal error as private can be accessed within it's own class
//echo "<br />";
echo $baseInstance->display(); //show all three as display is the method of the class.
echo "<br />";

$derivedInstance=new DerivedClass();
echo $derivedInstance->display(); //private variable of base class will not be shown.
?>

And the output is,

Public Variable
Public Variable Protected Variable Private Variable
Public Variable Protected Variable Protected Variable 2

Related Documents
http://arjudba.blogspot.com/2009/03/class-concepts-and-usage-syntax-in-php.html
http://arjudba.blogspot.com/2009/03/class-inheritance-example-in-php.html
http://arjudba.blogspot.com/2009/03/autoloading-objects-in-php.html
http://arjudba.blogspot.com/2009/03/constructors-and-destructors-in-php.html

Constructors and Destructors in php

From php5, constructors method can be declared within class. If you have declared a constructor in a class that the constructor method will be automatically called during creation of an instance of the class. So, you can declare a constructor whenver you think the initialization of an object must needed everytime after an instance is created.

Note that, you have both parent and child constructor corresponding to parent and child table. If you create an instance of the child table, parent constructor is not called implicitly. To call the parent constructor while creating child object, within child constructor you have to call parent constructor explicitly. Constructor is declared by keyword __construct (note that double underscore(__) is prepend before construct) and calling the parent constructor is done by parent::__construct().

As constructor is created for some initialization of the object, destructor comes for to destroy the object. Or in other word destructor is used to release any resources allocated by the object. The destructor method will be called as soon as all references to a particular object are removed or when the object is explicitly destroyed or in any order in shutdown sequence.

Below is an example of using both constructor and destructor.

<?php
class ParentClass {
function __construct(){
echo "This is the parent constructor. ". get_class($this);
echo "<br />";
}
}
class ChildClass extends ParentClass{
function __construct(){
echo "This is the child constructor. ".get_class($this);
echo "<br />";
}
function __destruct() {
echo "Destroying child object ";
}
}
$childInstance=new ChildClass();
?>

And the output on the browser is,

This is the child constructor. ChildClass
Destroying child object

Note that parent constructor is not called with the creation of child instance. In other to do so we have to call it within child constructor as shown below.

<?php
class ParentClass {
function __construct(){
echo "This is the parent constructor. ". get_class($this);
echo "<br />";
}
}
class ChildClass extends ParentClass{
function __construct(){
parent::__construct();
echo "This is the child constructor. ".get_class($this);
echo "<br />";
}
function __destruct() {
echo "Destroying child object. ". get_class($this);
}
}
$childInstance=new ChildClass();
?>

And output is below.

This is the parent constructor. ChildClass
This is the child constructor. ChildClass
Destroying child object. ChildClass

Related Documents
http://arjudba.blogspot.com/2009/03/class-concepts-and-usage-syntax-in-php.html
http://arjudba.blogspot.com/2009/03/class-inheritance-example-in-php.html
http://arjudba.blogspot.com/2009/03/autoloading-objects-in-php.html

Sunday, March 29, 2009

require_once and include_once in php

The include_once parameter is almost same as include and the require_once parameter is almost same as require. Both of require and include is described with example in http://arjudba.blogspot.com/2009/03/require-and-include-parameter-in-php.html. The only difference from include and require is that with require_once/include_once if the file is already included, it will not include again.

For example, if within your script you use below code then behavior will depend based on php version and OS type.

<?php
include_once 'test.php';
include_once 'Test.php';
?>

As of php 4.0 once test.php is included and then again Test.php is included regardless of OS. For case insensitive OS both test.php and Test.php point just one file but they are included twice. This behavior is changed in php 5.0. From php 5.0, on case insensitivity OS for example on windows machine test.php is included only once. But on unix file system they are included in each test.php and Test.php as they represent two different files.

Related Documents
http://arjudba.blogspot.com/2009/03/class-inheritance-example-in-php.html
http://arjudba.blogspot.com/2009/03/class-concepts-and-usage-syntax-in-php.html
http://arjudba.blogspot.com/2009/03/require-and-include-parameter-in-php.html

Require and Include parameter in Php

Suppose you have two php files named class1.php and class2.php and now from class1.php file you need to access the class class2 which is defined under class2.php.

With both include and require command you can include the class2.php and then uses the classes, objects, variables defined under class2.php.

Both "include" and "require" commands are almost identical except about how they handle failures. Both of them generates warning (E_WARNING) upon failure. But "require" results fatal error (E_ERROR) upon missing file and thus halt processing of the page. In contrast, "include" does processing rest of the lines of the file after issuing warning.

So if you want to process rest of the lines of the file after missing file then use include. If you want to halt processing rest of the lines of the file then use require.

Following is an example.

My class2.php file contents,

<?php
$test1="Momin";
$test2="Arju";
class Class2{
function display(){
echo "This is include/require test";
}
}
?>

And my class1.php file contents,

<?php
require 'Class2.php';
echo "It is in Class1: Variable from class2 $test1 $test2";
echo "<br />";
$class1Instance=new Class2();
$class1Instance->display();
?>

Now in browser class1.php displays,
It is in Class1: Variable from class2 Momin Arju
This is include/require test

Let's now change the class1.php file as below:

<?php
require 'Classnotfound.php';
echo "It is in Class1: Variable from class2 $test1 $test2";
echo "<br />";
$class1Instance=new Class2();
$class1Instance->display();
?>

Now on broswer running class2.php fails with message,
Warning: require(Classnotfound.php) [function.require]: failed to open stream: No such file or directory in C:\xampp\htdocs\class1.php on line 2

Fatal error: require() [function.require]: Failed opening required 'Classnotfound.php' (include_path='.;C:\xampp\php\pear\') in C:\xampp\htdocs\class1.php on line 2

Replacing require by include and see the differences.

<?php
include 'Classnotfound.php';
echo "It is in Class1: Variable from class2 $test1 $test2";
echo "<br />";
$class1Instance=new Class2();
$class1Instance->display();
?>

Warning: include(Classnotfound.php) [function.include]: failed to open stream: No such file or directory in C:\xampp\htdocs\class1.php on line 2

Warning: include() [function.include]: Failed opening 'Classnotfound.php' for inclusion (include_path='.;C:\xampp\php\pear\') in C:\xampp\htdocs\class1.php on line 2
It is in Class1: Variable from class2

Fatal error: Class 'Class2' not found in C:\xampp\htdocs\class1.php on line 5

Note that include display echos under class1.php but require does not.
Related Documents
http://arjudba.blogspot.com/2009/03/class-inheritance-example-in-php.html

http://arjudba.blogspot.com/2009/03/class-concepts-and-usage-syntax-in-php.html