For smart Primates & ROBOTS (oh and ALIENS ).

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

Tuesday, June 28, 2016

How to use $_POST in better way

How to use $_POST in better way.

Suppose there are 10 fields in a PHP webpage that's data are saving into database.
In that 10 fields 2 fields are empty and when in values are empty you want store "N/A" values are saving into database. 

Use below one line of code:
$myval = isset( $_POST['myvar'] ) ? $_POST['myvar'] : 'N/A'; 


You can use this logic in any website programming language.



Share:

Monday, February 08, 2016

XSS Exploits


XSS Exploits

It is XSS, It is Web site hacking. It is cross site scripting (XSS). 
The most usual form of Web site hacking . hackers force a site to perform certain actions like inject a client side scripting code (JavaScript) mixed with submitted content.


so that when a user visits a Web page with the submitted content, the malicious script gets downloaded automatically in his web browser and gets executed.

Using this types of hacking user's cookies and session stolen and sent to site of the attacker.
the user may get redirected to a targeted Web site for instance.
XSS may also be used for user account hacking. When the attacker is able to steal the session cookie value, he may be able to access to the user account as if it was the real user.

Prevention of XSS Exploits

XSS vulnerabilities can be avoided by properly encoding HTML using entities for <, >, " and '. Escaping of HTML characters on online forums can also be avoided by using bbcodes usually offered there.

The htmlpecialchars() function can be helpful in this regard as it converts content automatically into HTML entities. It also converts single quotes by using ENT_QUOTES as second argument. The strip_tags() function also removes PHP and HTML tags from string.
Share:

Friday, February 05, 2016

JSON parse in PHP

JSON parse in PHP



Suppose you want to parse listed below JSON data in PHP and you only needed to print objectId values. you can see here 3 records under merchants value "RPEZF3MRM39Z0"

-----------------------------------------------------------------------
{
"appId": "0QA16KMMVJAQR",
"merchants": {
"RPEZF3MRM39Z0": [{
"objectId": "O:S1MXC6FCY6GDW",
"type": "UPDATE",
"ts": 1453110818494
}, {
"objectId": "O:S1MXC6FCY6GDW",
"type": "UPDATE",
"ts": 1453110818913
}, {
"objectId": "P:SYD46NHH64EQG",
"type": "CREATE",
"ts": 1453110818913
}]
}
}
------------------------------------------------------------------------

php code:

suppose $st is hlding the above json data.

$json_a=json_decode($st,true);
foreach ( $json_a['merchants']['RPEZF3MRM39Z0'] as $objectId )
{
    echo $objectId['objectId']."</br>";
}




Share:

Tuesday, December 01, 2015

Remove version number from JS and CSS in WordPress

Problem:


How to Remove version number / querystring from JS and CSS in WordPress.

Solution:

goto your active theme folder and open functions.php file
and add below lines at the bottom.

function del_queryandversion_from_css_js( $style_or_js_url ) {
if ( strpos( $style_or_js_url, 'ver=' ) )
$css_js = remove_query_arg( 'ver', $style_or_js_url );
return $css_js;
}
add_filter( 'style_loader_src', 'del_queryandversion_from_css_js', 10 );
add_filter( 'script_loader_src', 'del_queryandversion_from_css_js', 10 );
Share:

Saturday, October 31, 2015

Mysql Database access using PDO

How to access Mysql Database using PDO:

PHP is changing day by day. in old days we were use mysql_connect(...) but now in current days it is not supported. current days we can use mysqli_connect(...). but it is better if we use PDO (PHP Data Object).

PHP Data Objects (PDO) is a very lightweight, consistent interface for accessing different types of databases in PHP. for this you simply tell the PDO database driver.

by using PDO you use the same functions to issue queries and fetch data in different types of database. PDO also remove all possibility of sql injections. for this it provide bind parameter facility.

Example:

Listed below full code that insert update delete list of all records. this code is in OOP based.


File: Db.php

<?php
class Db {
    private $pdo;
    private $stmt;

    function __construct() {
// set database setting here
$host='localhost'; $db='student_db'; $u='root'; $p='';
        try {
$this->pdo = new PDO("mysql:host={$host};dbname={$db}", $u,$p);
          $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch(PDOException $e) {
            $this->pdo = null;
echo $e->getMessage();
            return 'oops: ' . $e->getMessage();
        }
    }

    function __destruct() {
// release all resource
        $this->stmt = null;
        $this->pdo = null;
    }

// initialize prepare statement
    public function prepare_statement($sql) {
        $this->stmt = $this->pdo->prepare($sql);
    }

// bind parameter
    public function set_val($field_nm, $field_val) {
        $this->stmt->bindParam($field_nm, $field_val);
    }

// initialize prepare statement for update data using array
public function update_by_array($tbl_name, $where, $array_data) {
$sets="Update {$tbl_name} set ";
foreach ($array_data as $field => $value) {
$sets .= "{$field} = :{$field}, ";
}
$sets= substr($sets,0,-2).$where;
$this->prepare_statement($sets);
foreach ($array_data as $field => $value) {
$this->set_val(":{$field}", $value);
}
        return $this->exe_update_insert();
    }

//////// execute statement and return records from mysql
    public function get_record_exe_stat() {
        try {
            $this->stmt->execute();
            return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch(PDOException $e) {
echo $e->getMessage();
            $this->pdo = null;
            return 'oops: ' . $e->getMessage();
        }
    }

/// execute statement and return updated/inserted no of rows/row
    public function exe_update_insert() {
        try {
           
$this->stmt->execute();
//$this->stmt->debugDumpParams();
            return $this->stmt->rowCount();
        } catch(PDOException $e) {
//$this->stmt->debugDumpParams();
//echo $e->getMessage();
            $this->pdo = null;
            return 'oops: ' . $e->getMessage();
        }
    }

/// Return number of rows that are after delete/update/insert
    public function get_row_count() {
        try {
            $this->stmt->rowCount();
        } catch(PDOException $e) {
echo $e->getMessage();
            $this->pdo = null;
            return 0;
        }
    }
/// Return last auto increment id after insert record
    public function get_last_id() {
        try {
            return $this->pdo->lastInsertId();
        } catch(PDOException $e) {
$this->pdo = null;
            return 0;
        }
    }
/// Return records of sql query
    public function get_record_by_sql($sql)
    {
        try {
            $stmt = $this->pdo->prepare($sql);
            $stmt->execute();
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch(PDOException $e) {
echo $e->getMessage();
            $this->pdo = null;
            return 'oops: ' . $e->getMessage();
        }
    }
/// Insert record and return number of rows effected
    public function insert_by_sql($sql)
    {
        try {
            $stmt = $this->pdo->prepare($sql);
            $stmt->execute();
            return $stmt->rowCount();
        } catch(PDOException $e) {
echo $e->getMessage();
            $this->pdo = null;
            return 'oops: ' . $e->getMessage();
        }
    }
}



test.php

<?php
require_once('Db.php');
$db= new Db();
$i=0;

///// simple insert //////////
$number_of_rows_updated=$db->insert_by_sql("insert into std_info(std_full_nm,address,phone,class_cat) values ('xyz name','address123','1231231234','class 3')");

/////////////////////////insert by bind parameter prepare statement /////////////////////////////////////////////////////////
for($i=1;$i<=10;$i++) {
$std_full_nm = "AA".$i;
$address = "12/76 my address".$i;
$phone='12345678'.$i;
$class_cat='class'.$i;
$db->prepare_statement("insert into std_info(std_full_nm,address,phone,class_cat) values (:std_full_nm,:address,:phone,:class_cat)");
$db->set_val(":std_full_nm", $std_full_nm);
$db->set_val(":address", $address);
$db->set_val(":phone", $phone);
$db->set_val(":class_cat", $class_cat);
$up = $db->exe_update_insert();
if($up>=1){
$id=$db->get_last_id();
echo "Last id is =". $id."<br/>";
}
}

//////////////// return multiple row by prepare statement ////////////////////////////////////////////////////////////////
$id = "1";
$db->PrepareStatement("SELECT * FROM std_info WHERE std_id>= :id");
$db->set_val(":id", $id);
$userData = $db->get_record_exe_stat();
print_r($userData);
if (count($userData) < 1)
return;
for($i=0;$i<count($userData);$i++) {
echo $userData[$i]['std_id']."<br/>";
echo $userData[$i]['std_full_nm']."<br/>";
echo $userData[$i]['address']."<br/>";
echo $userData[$i]['phone']."<br/>";
echo $userData[$i]['class_cat']."<br/>";
echo "<hr/>";
}

///////////////////// return single row //////////////
$id = "1";
$db->PrepareStatement("SELECT * FROM std_info WHERE std_id= :id");
$db->set_val(":id", $id);
$userData = $db->get_record_exe_stat();
if (count($userData)>= 1) {
echo $userData[0]['std_id']."<br/>";
echo $userData[0]['std_full_nm']."<br/>";
echo $userData[0]['address']."<br/>";
echo $userData[0]['phone']."<br/>";
echo $userData[0]['class_cat']."<br/>";
echo "<hr/>";
}

///////////// update by using bind parameter ////////////////
$std_id = "1"; // Some ID to update
$std_full_nm = "zz";
$address = "55/76 my address";
$phone='0987654321';
$class_cat='10 class';

$db->prepare_statement("UPDATE std_info SET std_full_nm=:std_full_nm,address=:address,phone=:phone,class_cat=:class_cat WHERE std_id=:std_id");
$db->set_val(":std_id", $std_id);
$db->set_val(":std_full_nm", $std_full_nm);
$db->set_val(":address", $address);
$db->set_val(":phone", $phone);
$db->set_val(":class_cat", $class_cat);
$updated_row = $db->exe_update_insert();

///////////// update by using array ////////////////
$tbl_name='std_info';
$where=' WHERE std_id=1';
$sets = "";
$array_data = array(
'std_full_nm' => 'somename1',
'address' => 'someaddress1',
'phone' => 'Somephone1',
'class_cat' => 'Somecat1'
);
$db->update_by_array($tbl_name,$where, $array_data);

/////////////////// return records by simple sql //////////////
$id = "1";
$userData = $db->get_record_by_sql("SELECT * FROM std_info");
if (count($userData) < 1)
return;
for($i=0;$i<count($userData);$i++) {
echo $userData[$i]['std_id']."<br/>";
echo $userData[$i]['std_full_nm']."<br/>";
echo $userData[$i]['address']."<br/>";
echo $userData[$i]['phone']."<br/>";
echo $userData[$i]['class_cat']."<br/>";
echo "<hr/>";
}
Share:

Thursday, October 29, 2015

PDOException' with message 'SQLSTATE[42000 Syntax error or access violation: 1064

Problem:


How to fix following PHP PDO error
exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line


Solution:


It means you are missing small brackets ')' in your sql statement.
Share:

Wednesday, October 14, 2015

how to check if visitor is a robot or bot

Problem:

how to check if visitor is a robot or bot?

Solution:

Please use below code

Example:

$user_agent='';
if( !isset( $_SERVER['HTTP_USER_AGENT'])){
echo 'i m a Robot!';
die();
} else {
$user_agent=strtolower($_SERVER['HTTP_USER_AGENT']);
}

$robot='N';
if(strpos($user_agent,'bot')>0 || strpos($user_agent,'Bot')>0) {
    $robot='Y';
}

if($robot!='Y')
echo 'I am not a Robot';
else
echo 'I am a Robot';




Share:

Tuesday, October 13, 2015

Currency convertor

Problem:  

Some time you need to convert currency into different countries, so what you will do?

Solution: 

You can use yahooapi

Example: 

Use below code. the code is in PHP ou can easily convert it into VB.Net, Java, C# etc if you are good programmer.


function curr_convert($ffrom,$tto,$iinput) {
$yql_url = "http://query.yahooapis.com/v1/public/yql";
    $yql_query = 'select * from yahoo.finance.xchange where pair in ("'.$ffrom.$tto.'")';
    $yql_query_full_url = $yql_url . "?q=" . urlencode($yql_query);
    $yql_query_full_url .= "&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
    $yql_curl = curl_init($yql_query_full_url);
    curl_setopt($yql_curl, CURLOPT_RETURNTRANSFER,true);
    $yqlcurl_exec = curl_exec($yql_curl);
    $yql_json =  json_decode($yqlcurl_exec,true);
    $curr_output = (float) $iinput*$yql_json['query']['results']['rate']['Rate'];
    return $curr_output;
}
$result = curr_convert($ffrom = "USD", $tto = "INR", $iinput = 1);
echo '1 USD  = '.$result.' INR';

Share:

Monday, September 21, 2015

How to change or add some extra js file in Joomla

Problem:

How to change or add some extra js file in Joomla


Solution:


Open file from this location
libraries\joomla\document\html\renderer\head.php




Share:

Product color drop down is not sort order in magento admin panel

Problem:

In Magento admin Manage product section drop down is not in sort order.

Product color drop down is not sort order in magento admin panel


Go into backend magento admin ----> catalog ----> Manage Products --- under product colour when you click on a colour a dropdown will appear ---- then this will give you a list of colours
For some reason the colours are not in alphabetical order
See the image

drop down is not in sort order



Solution:

just open the file "app/design/adminhtml/default/default/template/catalog/product.phtml"
and paste below code. Please note that I am still working on this issue and updating the script so please wait. till than you can use the script

<script>
var $j = jQuery.noConflict();
function SortBox(x, y) {
    if (x.innerHTML == 'NA') {
        return 1;
    }
    else if (y.innerHTML == 'NA') {
        return -1;
    }
    return (x.innerHTML > y.innerHTML) ? 1 : -1;
}

function dook(){
 $j('select').each(function( index ) {
     $j(this).find('option').sort(SortBox).appendTo($(this));
});
}
var myVar = setInterval(function(){ dook() }, 5000);
</script>

Share:

Saturday, September 19, 2015

is it safe to remove version numbers from .js in vBulletin

Problem:

is it safe to remove version numbers from .js in vBulletin?

Solution:

yes, it is safe to delete version number from .js in vBulletin.
Share:

Sunday, August 09, 2015

Unable to access an error message corresponding to your field name

Problem:

While working with CodeIgniter in-build set validation with text box for ex: invalid email or empty filed you may face this error "Unable to access an error message corresponding to your field name"

It means you have not set correctly error setup.
$this->form_validation->set_rules('blink', 'Link', 'required|trim|');
Share:

Monday, June 01, 2015

Parse XML in PHP with Attributes

Problem:
How to Parse XML in PHP with Attributes
Listed below the XML data.
Suppose you have a url which produce below XML data on request and you want to parse it in PHP including it's attribute for ex:  spell id="168839" minCount="1" maxCount="1" etc.

See below XML for full information:
<?xml version="1.0" encoding="utf-8"?>
<wowhead><item id="114811">
  <name>Hexweave Leggings</name>
  <level>640</level>
  <quality id="4">Epic</quality>
  <class id="4">Armor</class>
  <subclass id="1">Cloth Armor</subclass>
  <icon displayId="132245">inv_cloth_draenorcrafted_d_01pants</icon>
  <inventorySlot id="7">Legs</inventorySlot>
  <htmlTooltip>
    <table>
      <tr>
        <td><!--nstart-->
          <b class="q4">Hexweave Leggings</b>
          <!--nend--><!--ndstart--><!--ndend-->
          <span style="color: #ffd100">
            <br />
            Item Level<!--ilvl-->640</span>
          <br />
          <!--bo-->Binds when equipped
          <br />
          Unique-Equipped: Warlords Crafted (3)
          <table width="100%">
            <tr>
              <td>Legs</td>
              <th>Cloth</th>
            </tr>
          </table>
          <span><!--amr-->83 Armor</span>
          <br />
          <!--re-->
          <span class="q2">&lt;Random enchantment&gt;</span>
          <br />
          <span><!--stat5-->+184 Intellect</span>
          <br />
          <span><!--stat7-->+275 Stamina</span>
          <!--ebstats--><!--egstats--><!--e--><!--ps-->
          <br />
          Durability 120 / 120</td>
      </tr>
    </table>
    <table>
      <tr>
        <td>Requires Level<!--rlvl-->91
          <div class="whtt-sellprice">Sell Price:
            <span class="moneygold">41</span>
            <span class="moneysilver">61</span>
            <span class="moneycopper">90</span>
          </div>
        </td>
      </tr>
    </table>
  </htmlTooltip>
  <json>"appearances":{"6":[132245,""],"7":[132269,""],"8":[132254,""]},"armor":83,"bonustrees":[184],"classs":4,"displayid":132245,"flags2":8192,"id":114811,"level":640,"name":"4Hexweave Leggings","reqlevel":91,"slot":7,"slotbak":7,"source":[1],"sourcemore":[{"c":11,"icon":"inv_cloth_draenorcrafted_d_01pants","n":"Hexweave Leggings","s":197,"t":6,"ti":168839}],"specs":[64,256,63,62,257,265,258,266,267],"subclass":1</json>
  <jsonEquip>"appearances":{"6":[132245,""],"7":[132269,""],"8":[132254,""]},"armor":83,"avgbuyout":53990000,"displayid":132245,"dura":120,"int":184,"reqlevel":91,"sellprice":416190,"slotbak":7,"sta":275</jsonEquip>
  <createdBy>
    <spell id="168839" name="Hexweave Leggings" icon="inv_cloth_draenorcrafted_d_01pants" minCount="1" maxCount="1">
      <reagent id="111556" name="Hexweave Cloth" quality="2" icon="inv_tailoring_hexweavethread" count="100"/>
      <reagent id="110609" name="Raw Beast Hide" quality="1" icon="inv_misc_nativebeastskin" count="4"/>
    </spell>
  </createdBy>
  <link>http://www.wowhead.com/item=114811</link>
  </item></wowhead>


Solution:

Using simplexml_load_file we can parse XMl data.

Example:

<?php
$url='http://www.wowhead.com/item=114811&xml';
$xml = simplexml_load_file($url) or die("feed not loading");
foreach($xml->item  as $items){
    echo $items->name . "<br>";
echo $items->level . "<br>";
echo $items->quality . "<br>";
echo $items->quality['id'] . "<br>";
echo $items->class . "<br>";
echo $items->class['id'] . "<br>";
echo $items->subclass . "<br>";
echo $items->subclass['id'] . "<br>";
echo $items->icon . "<br>";
echo $items->icon['displayId'] . "<br>";
echo $items->inventorySlot . "<br>";
echo $items->inventorySlot['id'] . "<br>";
echo $items->htmlTooltip . "<br>";
echo $items->json . "<br>";
echo $items->jsonEquip . "<br>";
echo $items->createdBy->spell  . " : ";
echo $items->createdBy->spell['id']  ." : ";
echo $items->createdBy->spell['name']  ." : ";
echo $items->createdBy->spell['icon']  . " : ";
echo $items->createdBy->spell['minCount']  ." : ";
echo $items->createdBy->spell['maxCount']  . "<br>";
$created_by_count=0;
foreach($items->createdBy->spell  as $myspel){
if($myspel->count()>=1) {
    foreach($myspel as $child) {
                  $created_by_count++;
      echo $child->getName(). ' : '. $child['id']. ' : ' .$child['name'] . ' : ' . $child['quality']. ' : ' . $child['icon']. ' : ' . $child['count'] . '<br/>';
}
  }
  echo 'Count createdBy='.$created_by_count. "<br>";
echo $items->link . "<br>";
}
}
?>
Share:

Tuesday, May 26, 2015

Scrolling paging in PHP

Problem:

Database paging without paging page number.  This is same as Facebook and Tumblr like paging.

Solution:

By using Ajax you can achieve that like scroll paging.

Example:

Use below code. Assuming 1 to 10th records already showing.

index.php
<script type="text/javascript" src="jquery-1.6.js"></script>
<div id="mydiv">
<p>Database paging </p><p>without paging</p><p>page number</p><p>This is same as Facebook</p><p>and Tumblr.</p><p>like paging.</p><p>Assuming 1 to 10th records already showing.</p> <p>Next 11th to end of records will show when scroll page.</p>

<p>1 record</p><p>2 record</p><p>3 record</p><p>4 record</p><p>5 record</p><p>6 record</p><p>7 record</p><p>8 record</p><p>9 record</p><p>10 record</p>   </div>

<a id="loading_img" style="position:fixed; z-index: 99;bottom: 15px; right: 10px; display:none;">Loading... <img src="ajax-loader.gif" /></a>

<script type="text/javascript">
var page = 1;
$(window).scroll(function () {
currentX = $(window).scrollTop();
if  ($(window).scrollTop() == $(document).height() - $(window).height()){
$('a#loading_img').show('fast');
$.get('mydb.php?page=' + page, function(data) {
$('#mydiv').append(data);
$('a#loading_img').hide('fast');
}
);
page++;
}
});
</script>



mydb.php

<?php
$mysqli = new mysqli('localhost', 'root', '','mydb');
$pg=$_GET['page'];
$pg=$pg*10;
$sql='SELECT *FROM book_wise_test ORDER BY book_wise_test_id LIMIT '.$pg .', 10';
$result  = $mysqli->query($sql);
while($row = $result->fetch_assoc()) {
$book_wise_test_id=$row['book_wise_test_id'];
$book_nm=$row['book_nm'];
echo $book_wise_test_id.'======'.$book_nm.'<br/><br/>';
}
?>
Share:

Monday, May 11, 2015

Message: Undefined variable: 0 in CodeIgniter PHP

Problem:

Sometime while working with CodeIngiter / PHP you may encounter "Undefined variable: 0" error.
It surprise to that is "0" (Zero) could be a variable!

Solution:

This "Undefined variable: 0" error come when you use double dollar sign in variable. so remove one dollar ($) sign from variable and error will gone.

Example:

See the below code, specially in red color, it having $$ sign:

$data = array( 'u_login' => $row->u_login,
                        'user_type_id' => $user_type_id,
'user_id'=>$row->user_id,
'transporter_id'=>$transporter_id,
'limit_cr'=>$limit_cr,
'u_c_date'=>$row->u_c_date,
'total_trucks'=>$total_trucks,
'total_liter'=>$total_liter,
'pump_id'=> $$pump_id
                        );

jut remove one $ sign.
Share:

Wednesday, May 06, 2015

How to convert eps file to jpg file

Problem:

How to convert .eps file to .jpg file

Solution:

It is simple, use ImageMagick and below java code. if you expert in PHP or .Net then you can easily convert it same as me.

Example:

import="java.util.*"%>  
import="java.io.*"%>
 
try
    {
        Runtime runTime = Runtime.getRuntime();
        Process process = runTime.exec ("C:/Program Files/ImageMagick-6.5.4-Q16/convert.exe c:/Art1.eps c:/art1.jpg");
        //InputStream inputStream = process.getInputStream();
        //InputStreamReader   inputStreamReader = new InputStreamReader (inputStream);
        //BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
        ///String line = null;
        //while ( (line = bufferedReader.readLine()) != null )
        //    System.out.println(line);
        int exitVal = process.waitFor();
        System.out.println ("Process exitValue:  " + exitVal );
    }
    catch (Throwable t)
    {
        t.printStackTrace();
    }
Share:

Friday, April 17, 2015

session destroyed after redirect in codeigniter

Problem:

Working CodeIgniter framework you can face the session problem. the problem is when you storing the values in session and redirect the page. then session destroyed automatically, it is loosing session data even you have properly loaded session library $this->load->library('session') in constructor.

see the below code:

public function myset() 
{
        $this->session->set_userdata('mydata', 'data');
        redirect('/', 'refresh');
}


function index()
{
          // loosing here data
          $mydata = $this->session->userdata('mydata');

}






Solution:

As we are seeing many new frameworks are coming today. but the Mother and base of all frameworks is Core PHP,  So we must have good knowledge about Core PHP. Here I have solved this session problem by Core PHP.

Example:

session_start();
public function myset() 
{
        $_SESSION['mydata']='data'
        redirect('/', 'refresh');
}


function index()
{      $mydata='';
        if(isset($_SESSION['mydata']) && !empty($_SESSION['mydata'])) {
                  $mydata= $_SESSION['mydata']);
        }

}

Share:

Wednesday, April 15, 2015

How to use multilanguage in CodeIgniter

Problem:

Suppose you want to use Italian language in CodeIgniter then how to do it?



Solution:

CodeIgniter provide a facility that you can store the predefined words in array in separate files. after that you can use it as per your requirements.

Example:

1- create a folder name "italian" under "application\language".
2- under this folder create a "italian_lang.php" file as below matter. change it's matter as per your requirements.
<?php
$lang['home_slide_1']        = "Rendi <span>unici</span> i tuoi parastinchi";
$lang['home_latuaidea_title']        = "La tua <br/>idea";
/// and many more....
?>
now your file is created, now the question is that how to use it?
4- in view where you want to write italian text at the top of file load this file as below method:
$this->lang->load('italian', 'italian');


<?php echo $this->lang->line('home_slide_1');?>
<?php echo $this->lang->line('home_latuaidea_title');?>


Share:

Friday, April 10, 2015

Run custom sql query in CakePHP 3.0

Problem:

How to Run custom sql query in CakePHP 3.0

Solution & Example:

File : src\Model\Table\ArticlesTable.php
<?php
namespace App\Model\Table;

use Cake\ORM\Table;
use Cake\Datasource\ConnectionManager;
class ArticlesTable extends Table
{
    var $conn;
    public function initialize(array $config) {
        $this->conn = ConnectionManager::get('default');
    }
    function get_all_users($id) {
        $stmt = $this->conn->prepare('SELECT * from users WHERE id>= :id');
        $stmt->bind( ['id' => $id], ['id' => 'integer']);
        $stmt->execute();
        return $stmt->fetchAll('assoc');
     } 
}
?>

File: src\Controller\ArticlesController.php
<?php
namespace App\Controller;

use Cake\Core\Configure;
use Cake\Network\Exception\NotFoundException;
use Cake\View\Exception\MissingTemplateException;
use Cake\ORM\TableRegistry;
use Cake\Datasource\ConnectionManager;
//use MyClass\MyClass;
use MyLib\UtilClass;

 class ArticlesController extends AppController
 {
     public $helpers = array('Html', 'Form');
     public function index() {

    }
    public function showarticles(){
         $data = $this->Articles->get_all_users(3);
         $this->set('data',$data);
    }
}


File: src\Template\Articles\showarticles.ctp
<?php
foreach ($data as $row){
               echo '<br/>'.$row['username']. '-------' . $row['password'];
         }
?>









Share:

Wednesday, April 08, 2015

How to create own custom class in cakephp 3.0

Problem:

How to use own custom class or library class in CakePHP 3.0
If you have own useful library and you want to use it in your CakePHP 3.0 MVC Framework then follow below steps.


Solution:

If you have good knowledge of Core PHP then It will be easy to create own custom class in CakePHP 3.0 and use it. follow below steps:

1# Create the folder "MyLib" at root of CakePHP 3.0 structure where bin,config,logs folders are showing. you can also create it in the "vendor" folder but I think we should not create in there.

2# Create "UtilClass.php" file in the "MyLib" folder.

3# And last use it in your controller with it's path.

Example:

1# Create the folder "MyLib" at root of cakephp 3.0 structure where bin,config,logs folders are showing.

2# Create "UtilClass.php" file in the "MyLib" folder with below code:
<?php
namespace MyLib; //it is important,it is folder name
class UtilClass
{
    public function show()
    {
        return 'I am from my custom class in cakephp 3.0';
    }
}
?>


3# Use is as below code in any controller:
<?php
use MyLib\UtilClass;
 class TransportersController extends AppController
 {
     public function index() {

    }

    public function showtransporter(){
      require_once(ROOT .DS. "MyLib" . DS . "UtilClass.php");
      $util_obj = new UtilClass();
      echo $util_obj->show();

  }
}
?>
Share:

Ads Inside Post

Powered by Blogger.

Archive