Freedom To Learn ……….

Writing, to me, is simply thinking through my fingers. — Isaac Asimov


Leave a comment

What is Difference between MySQL delete and truncate table

This very common question in interviews.  Both remove records from the table, so what is the difference.

  • Delete :
                         Syntax :  Delete from TableName [where condition];
    Deletes record  from table . But doesn’t reset the auto_increment
    DELETE operations are transaction-safe and logged, which means DELETE can be rolled back.
    DELETE will fire any ON DELETE triggers.DELETE will fail if foreign key constraints are broken.
  • Truncate :
                         Syntax :  truncate table  TableName;
    Deletes all record  from table. Reset the auto_increment.
    TRUNCATE cannot be done inside a transaction and can’t be rolled back.
    Because TRUNCATE is not logged recovering a mistakenly TRUNCATEd table is a much bigger problem than recovering from a DELETE. Truncate the Trigger is not fired.

    There are difference in Delete and Truncate:
    1. Delete use for delete row by row but truncate will delete the entire table.
    2. In Truncate rollback not possible.
    3. Value of Auto Increment will reset from starting after use of Truncate not in Delete.
    4. Truncate is a DDL(Data Definition Language) command and Delete is a DML(Data Manipulation Language) command.
    5. When Delete the Particular row the Corresponding Delete Trigger(if exists) Fire.In Case of Truncate the      Trigger is not fired.

    But I found issue with both command, they will take time to execute when data is more than 2GB. So , I will prefer to Drop table & again create it.
    Before dropping table, export the structure of table using PHPMYADMIN or database administrative tools in sql file, so we can import the sql file, which will creates table structure.


Leave a comment

Yii Tips and Tricks

While working on Project base on Yii framework, got some questions/problems. After searching couple of hours found solutions,So sharing here….,

  • How can change default action of Yii controller?

Ans:- Declare variable  ‘ public $defaultAction = ‘actioname'; ” in controller.
e.g.:-  class LoginController extends Controller
{             public $defaultAction = ‘login';

  • How to change the default Controller of site in Yii?

Ans:- add ” ‘defaultController’=>’module/controller/action ”  in main.config

  • How to change the default theme of site?

    Ans:- add ” ‘theme’=>’theme-name ”  in main.config

  • How do I create a linked image or CHtml:link with an image?

    Ans:-
    $imghtml=CHtml::image(Yii::app()->theme->baseUrl.’/images/settings-icon.png’);
    echo CHtml::link($imghtml,Yii::app()->createAbsoluteUrl(‘/controller/action/’),array(“class”=>”classname”));

  • How to change the layout in contrlller?

    call  $this->layout = “//layouts/name” if you want change on particular action, or declare variable as,
    public $layout = “//layouts/name”;

  • How to set the time zone in Yii?

 We can set the time zone index.php using php function ,       date_default_timezone_set(‘Asia/Calcutta’);
But I found another way,
Open main.php & write as key =>pair value like,

return array(
‘timeZone’ => ‘Asia/Calcutta’,
……………….
……..
);


3 Comments

URL rewriting in Yii to hide index.php

Hi Folks,

I am using Yii -yes it is,  MVC framework for new project in PHP.
I started  learning  yii from the official site of yii. I found it is hard to start the work on yii, specially who don’t have
knowledge of MVC framework like Code Igniter (CI) or Zend. It take some time to understand the MVC in yii, as nobody of  us is familler with CI or zend.

Finally we figure out the basics of  Yii. While working on basic of Yii, I want to rewrite the url to SEO friendly.
So I started to search on google, forum got useful information here http://www.yiiframework.com/doc/guide/1.1/en/topics.url

To hide the index.php from url I did changes in config/main.php  as shown below,

‘urlManager’=>array(
                              ‘urlFormat’=>’path’,
                              ‘showScriptName’=>false,
                              ‘rules’=>array(
                                                ‘<controller:\w+>/<id:\d+>’=>'<controller>/view’,
                                               ‘<controller:\w+>/<action:\w+>/<id:\d+>’=>'<controller>/<action>’,
                                              ‘<controller:\w+>/<action:\w+>’=>'<controller>/<action>’,
                                             ),
), 

and I created new .htaccess file in the same directory as my index.php file shown as below,

RewriteEngine  On
RewriteBase  /
RewriteCond   %{REQUEST_FILENAME} !-f
RewriteCond   %{REQUEST_FILENAME} !-d
RewriteRule    ^(.*)\?*$ index.php/$1 [L,QSA]

 You can change the ”RewriteBase /’  as per project location like if project is located in ‘folder1′ of webroot.
then it change like as    RewriteBase  /folder1

Note that my urlManager has the line:

‘showScriptName’=>false,

That will make sure your auto-generated links (CHtml::link or zii.widgets.CMenu) do not have index.php in them. This will not work without the .htaccess file. The reason is that the .htaccess file rewrites the url to point to index.php/$1 so that Yii actually gets the request properly. You will not see the index.php in the url at any time though.

Yii hide index.php from url, geting 404 error

Now it’s time to update this post, While working with Cest Os in local network, I did same thing to rewrite the url.
but it don’t work, the apache rewrite modue is enabled, all things are perfect ,
but still I am geting 404 error while while accessing the page.
After googling couple hours , I found the I have problem in ‘httpd.conf’

Options Indexes FollowSymLinks
#this is the part that needs changing. I changed ‘None’ to ‘All’
AllowOverride All
Order allow,deny
allow from all

this allows virtual host rewrite index.


Leave a comment

Include php file On all the pages of php

I need to include a files in all of your site’s pages? Normally, you’d use require() or include(). But do I really want to manually past the include code in every page?

This may be at the start of page or end of page.

There’s the little known PHP directive auto_prepend_file and auto_append_file. What are PHP directives? They’re essential global PHP settings that are defined in you php.ini file. There is surprisingly little information about these methods out there, but luckily they aren’t too difficult to work with.

In the php.ini file, we can implement like this,

; Automatically add files before or after any PHP document.
auto_prepend_file = D:/wamp/www/includefileatstart.php
auto_append_file =  D:/wamp/www/includefileatend.php

For Linux system it is something like this

/home/username/public_html/includefile.php

For me this will not work on Wamp…  ;)

So I have to find another way, … so we did with the help of .htaccess.. we can set it at runtime…

Create .htaccess file in www folder.

php_value auto_prepend_file D:/wamp/www/includefileatstart.php
php_value auto_append_file D:/wamp/www/includefileatend.php

For Linux system it is something like this

/home/username/public_html/includefile.php

Create file the file which you want to include  ‘includefileatstart.php’ and ‘includefileatend.php’

includefileatstart.php

<?php

echo “included at the start of program <br />”;

?>

includefileatend.php

<?php

echo “included at the end of program<br />”;

?>

Create test file:-  test.php

<?php

echo “this is body of page<br>”;

?>
You can download here… http://code.google.com/p/project-php-pretend-append-file/downloads/list

I have created function file & this is included at the start.
Like this :- includefunction.php

<?php
function pa($a,$d=0)
{
echo “<pre>”;
print_r($a);
echo “</pre>”;
if($d==1) die;
}
?>
Tested like this, test2.php
<?php
$array=array(‘1′,’2′,’3′,’4′,’5′,’6′);

pa($array);

//pa($array,1);

?>

this will o/p the array.


Leave a comment

PHP security tips

NEVER trust user input

User the following validation methods for input.

<?php
$username = mysql_real_escape_string($_POST[‘username’]);
$password = mysql_real_escape_string($_POST[‘password’]);
// Query database to check if there are any matching users
$query = “SELECT * FROM users WHERE user=’$username’ AND   password=’$password'”;
mysql_query($query);

$variable = htmlentities($_GET[‘page’], ENT_QUOTES, ‘UTF-8′);
// or even more secure
$variable = strip_tags($_GET[‘page’]);
?>


4 Comments

Joomla1.5 manually add admin user

Hi ,…
When we work with joomla site… we should have the back end access.. i.e.  super-admin access.

But we don’t have that…. may be client may forgot to give you or given wrong details…

So need to create new one.. or just change the password in database of joomla site.

We  faced the situation where client has given the correct FTP details… but wrong admin details.. & clinet want some urgent changes on the site.. .. so we have just created simple script in PHP .. which create new User for your joomla using PHP & mysql….

<?php
	error_reporting(-1);
	ini_set("display_error",1);	
?>

<html>
<head>
<title>Joomla1.5 User Creater</title>
<style type="text/css">
#user{	
	margin:0 auto;
	width:500px;	
}
#user td{
	height:30px;
}
h1,h2{
	text-align:center;
}
</style>
</head>
<body>
<form name="joomadduser" method="POST">
	<table cellspacing="0" cellpadding="0"  id="user">
	
<?php
	
if(isset($_POST['submit']))
{			
	$host=trim($_POST['hostname']);
	$dbuser=trim($_POST['dbusername']);
	$dbpassword=trim($_POST['dbpassword']);
	$db=trim($_POST['dbname']);
	$tbprefix=trim($_POST['tbprefix']);	
	
	/****Custom Username & Password*****/
	$username=trim($_POST['username']);
	$password=md5(trim($_POST['password']));	
	$email=trim($_POST['email']);
	
	/********User Creation time********/
	$registerDate=@date('Y-m-d H:i:s');
		
	$con=mysql_connect($host,$dbuser,$dbpassword) or die(mysql_error().'Sql error , Connection failed');
	if($con)
	{
		/***insert admin user in table ***/
		mysql_select_db($db) or die(mysql_error()."Not able to connect to Database");
		$sql="insert INTO ".$tbprefix."users (name,username,email,password,usertype,block,sendEmail,gid,registerDate,lastvisitDate,activation,params) "."values ('$username','$username','$email','$password','Super Administrator',0,1,25,'$registerDate','$registerDate','','')";	
		
		mysql_query($sql) or die(mysql_error()."Not able to create admin");
		$adminid=mysql_insert_id($con);				
		
		/***insert admin user id  into usergroup section table ***/		
		$query="insert into ".$tbprefix."core_acl_aro (section_value,value,order_value,name,hidden) VALUES ('users','$adminid',0,'$username',0)";
		mysql_query($query) or die(mysql_error()."Not able to add in section");
		$sectionid=mysql_insert_id($con);
		
		/***insert admin user id  into usergroup ***/
		$query="insert into ".$tbprefix."core_acl_groups_aro_map VALUES (25,'',$sectionid)";
		if(mysql_query($query)  or die(mysql_error()."Not able to add in group"))
		{
			echo "<tr><td align='center'><h1>New User Created Succesfully.</h1><h2>Details As Below:</h2>";	
			echo "Username:-".$username."<br \>";	
			echo "Password:-".trim($_POST['dbpassword'])."</td></tr>";				
		}		
	}
}	
else
{	
?>

		<tr>
			<td colspan="2"><h1>Joomla1.5 manually add admin user</h1></td>			
		</tr>
		<tr>
			<td colspan="2" height="35"></td>
		</tr>
		<tr>
			<td colspan="2" height="35"><h2>Enter Database Details: </h2></td>			
		</tr>
		<tr>
			<td>Host Name</td>
			<td><input value="" name="hostname"></td>
		</tr>		
		<tr>
			<td>Database Username</td>
			<td><input value="" name="dbusername" id="dbusername" value=""></td>
		</tr>
		<tr>
			<td>Database Password</td>
			<td><input type="text" name="dbpassword" value=""></td>
		</tr>
		<tr>
			<td>Database Name</td>
			<td><input value="" name="dbname" id="dbname" value=""></td>
		</tr>
		<tr>
			<td>Table Prefix</td>
			<td><input value="" name="tbprefix" value="jos_"></td>
		</tr>
		<tr>
			<td colspan="2"></td>			
		</tr>
		
		<tr>
			<td colspan="2" height="35"><h2>Enter User Details: </h2></td>			
		</tr>				
		<tr>
			<td>New Joomla Username</td>
			<td><input value="" name="username" value=""></td>
		</tr>
		<tr>
			<td>New Joomla Password</td>
			<td><input type="text" name="password" value=""></td>
		</tr>
		<tr>
			<td>Email Id</td>
			<td><input type="text" name="email" value=""></td>
		</tr>
		<tr><td colspan="2"></td></tr>
		<tr>
			<td></td>
			<td><input type="submit" name="submit" value="Submit"></td>
		</tr>
<?php
}
?>
</table>
	</form>
</body>
</html>


Leave a comment

Doing page redirection in PHP

Hi,

In php header() function is used to redirect page.
Syntax:-
header(“Location:newpage.php”);

header() must be used before sending any output either by HTML, blank lines or from PHP.
Otherwise error message “header already sent” error shown.

To overcome this problem, we can use  javascript for doing page redirection as below

window.location=”newpage.php”;

But if the JavaScript is disabled by the browser, then it will not work.

So we need can write a function in PHP like below,

<?php
function redirect($url=””)
{
if (!headers_sent()) header(“Location:$url”);
else
echo “<script>window.location=\”$url\”; </script>
<noscript>Automatic redirection didn’t work.<br />
<a href=\”$url\”>Click here to go to newpage.</a> </noscript>”;
}
$url=’newpage.com';
redirect($url);
?>

Follow

Get every new post delivered to your Inbox.