Send json in HTTP POST request by CURL php

A simple post operation by php curl. And send some json data.

//extract data from the post
extract($_POST);

//set POST variables
$url = 'http://aajit.com/apipath';
$jsodata='{"to":"foo", "msg":"bar", "token":"blah"}';
$fields_string ="aajgw=".$jsodata;

//open connection
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 1); // 1 for number of params (aajgw)
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//execute post
$result = curl_exec($ch);
echo $result;

//close connection
curl_close($ch);

Pass data from controller to view in magento

It’s may be very easy for Zend framework user But, I sow some magento developer fighting to pass data from controller to view.
To pass data from controller to view in magento you have to create a empty model(if your mod don’t have a varient object model) which extends to varient object. Magento use magic getter magic setter so you can pass value by setAnyname() and getAnyname() thus functions will be auto defines by Zend like many other framework do. :-)

Model file:

Packname_Modulename_Model_Viewinfo extends Varien_Object{

}

Controller function:

public function indexAction()
{
  $bla = Mage::getSingleton('Modulename/viewinfo');
  $bla->setMsg("Thank You for your visit!");
  $this->loadLayout();
  $this->renderLayout();
}

Now in your View .phtml file add:

<?php $blas = Mage::getSingleton('Modulename/viewinfo'); ?>
<?php echo $blas->getMsg(); ?>

Nobody beat us Fry us and eat us

Want MySQL FullText Search with InnDB Huh?

MySQL FullText indexing is only available if database table type MyISAM. But, MyISAM table type does not support Foreign keys. InnoDB table type support Foreign keys but does not support FullText. So I have to use a trick to implement fulltext search for a InnoDB type table. I have created a temporary MyISAM table which is identical to my InnoDB table and deleted that table after search complete. check this out……

Provide the search term and limit for search result in function’s parameter.

<?php

function fulltxt_search($q,$lim1,$lim2){ 

$terms =trim(stripslashes(strip_tags($q)));
$rhtml="";
if(empty($terms)){

   $rhtml.= "\n".'<p>No search term entered.</p>';

}else{

   // SQL injection prevention (double quote mark is allowed here but should probably be disallowed)

   $terms = strtr($terms, ',/\*&()$%^@~`?;', '               ');

   $terms = trim($terms);

   $terms = str_replace('#180', '', $terms);

   $rhtml.= "\n".'<p>Searching for <i>'.htmlspecialchars($terms).'</i>... </p>';

   $key = 'text_index';

   // Beware of the re-definition of $s in this query.

   $terms = html_entity_decode($terms, ENT_QUOTES);

	mysql_query('CREATE TEMPORARY TABLE `tbl_mirror` (FULLTEXT INDEX (`info`)) Engine=MyISAM SELECT * FROM `values`');

   if(!($res = @mysql_query('SELECT * FROM `tbl_mirror` WHERE MATCH(`info`) AGAINST ("'.$terms.'") LIMIT '.$lim1.', '.$lim2.';')or die(mysql_error()))){

	  mysql_query('DROP TEMPORARY TABLE tbl_mirror;')or die(mysql_error());
      echo "\n".'<p>No match for: <i class="red">'.$terms.'</i></p>';

   }else{

	mysql_query('DROP TEMPORARY TABLE tbl_mirror;')or die(mysql_error());

      if(@mysql_num_rows($res) == 0){

        $rhtml.="\n".'<p>The search engine cannot find the page you are looking for.</p>';

        $rhtml.="\n".'<p>This could be because it could not find any pages containing <i>'.$terms.'</i>';

        $rhtml.="\n".'<p>Alternatively, it might have found too many pages, and could not decide which one you wanted.</p>';

      }else{

         $i = 0;

         while($row = mysql_fetch_array($res)){

            $s = substr(stristr(strip_tags($row['info']), $terms), 0, 120);
            $i++;
	    $out[]=$row;
            $rhtml.="\n".'<p>'.$i.'.) <a href="results.php?rez_id='.$row['f_id'].'">'.htmlentities($row['info']).' - '.$row['f_id'].'</a><br />... '.$s.'...'.$row['id'].'/'.$row['e_id'].'...</p>';

         }

      }

   }

}

return $rhtml;
}
?>

Export/Backup MySQL Database like phpMyAdmin

Call the function with database name and a path to save backup( leave blank for current dir)

<?php
function db_bkf($dbname, $path=''){

ini_set('display_errors',1);
error_reporting(E_ALL);
echo 'Backuping database....';
$drop=0;

mysql_connect('localhost', 'root', '');

mysql_select_db("logs");

$hostname='localhost'; $username='root'; $password='';

$backupFile = $path.$dbname . date("Y-m-d-H-i-s") . '.sql';

$tab_status = mysql_query("SHOW TABLE STATUS");

while($all = mysql_fetch_assoc($tab_status)):

    $tbl_stat[$all['Name']] = $all['Auto_increment'];

endwhile;

$backup='';

$tables = mysql_query("SHOW TABLES FROM $dbname");

echo ($tables=="")?"No db table found !":count($tables)." Tables";

while($tabs = mysql_fetch_row($tables)):

$droptbl=(($drop==1)?"DROP IF EXISTS TABLE `".$tabs[0]."`;":"");

    $backup .= "--\n--Table structure for `$tabs[0]`\n--\n\n".$droptbl."\nCREATE TABLE IF NOT EXISTS `$tabs[0]` (";

    $res = mysql_query("SHOW CREATE TABLE $tabs[0]");

    while($all = mysql_fetch_assoc($res)):

        $str = str_replace("CREATE TABLE `$tabs[0]` (", "", $all['Create Table']);

        $str = str_replace(",", ",", $str);

        $str2 = str_replace("`) ) TYPE=MyISAM ", "`)\n ) TYPE=MyISAM ", $str);

        $backup .= $str2." AUTO_INCREMENT=".$tbl_stat[$tabs[0]].";\n\n";

    endwhile;

    $backup .= "--\n--Data to be executed for table `$tabs[0]`\n--\n\n";

    $data = mysql_query("SELECT * FROM $tabs[0]");

    while($dt = mysql_fetch_row($data)):

        $backup .= "INSERT INTO `$tabs[0]` VALUES('$dt[0]'";

        for($i=1; $i<sizeof($dt); $i++):

            $backup .= ", '$dt[$i]'";

        endfor;

        $backup .= ");\n";

    endwhile;

    $backup .= "\n-- --------------------------------------------------------\n\n";

endwhile;

$fh=fopen($backupFile,'w') or die("Backup not done! file error");
fwrite($fh, $backup);
fclose($fh);
echo "<br />Backup Complete !"; 

}
?>

aaJ TECH LOG

Md.Ashraful Abedein
  ©2010 www.ashraful.tk