Wednesday, 9 April 2014

Saving PHP Code in MYSQL database and executing the Code

In my latest project I got a task to save php code as it is into the mysql database and execute it on the userside by fetching from the database. If we use the normal method of saving and retreiving it will Fail because Php syntaxed code can't be saved as it is because it may break the sql code . So we have to use two php built in functions to make it possible.
 mysql_real_escape_string($string);
This function is used to save Php syntaxed code to the database without sql code breaking.

eval($string);
This function is used to excute the fetched content as php code.

Because normally If we retrive value from databse using normal method it only consider the result as a string and will display the whole php code without executing it. But thie eval() function will make it executable as our normal php code.

So Before trying to save Php code we have to know about eval() function and What should be the input given to it for its successful exceution.

For its successful execution we have to give it an input like
 for eg:


 echo $compname; 
 echo '|';
 echo $country; 
 echo '|';
 echo $state; 
 echo '|';
 echo $city; 
 echo '|';
 echo $location; 


Every string should be a php type code ending with semicolon. and for strings don't forget to put  opening and closing apostrophies :-

echo 'string';

So just give this above type text for saving and while saving use
$datatosave= mysql_real_escape_string($string);
$query="insert query here"//;
to save to database.

And during retreiving for eg:-


$query="Select query to retreive";
$row=mysql_fetch_assoc($query);
$description=$row['description'];

Dont  forget to assign values to variables which we have given in the php code:-
$compname,$country,$state,$city,$location.etc:_

If we assign values to these variables like:

$compname="Mycompany";
$country="India";
$state="Kerala";
$city="Alleppey';
$location="Nedumudy";

Then it is executed like :

<?php  echo eval($description);  ?>

You will get the php variables executed. and result will be like:

Mycompany|India|Kerala|Alleppey|Nedumudy


Hope you Understand it... have a great day ;-)