Friday, September 28, 2012

QR Code generation with PHP

Generating QR code with PHP is very easy. I had downloaded this library couple of days back..

Please download the class file BarcodeQR.php from http://www.shayanderson.com/


// Include the Library
include("BarcodeQR.php");

// Instantiate the BarcodeQR Object
$qr = new BarcodeQR();

// Info which will be put into the QR
$qr_text = "Account_no: 12345\nUsername: rocker\nEmail_address: test@gmail.com\nContact_no: 9988776655";

// Set object property
$qr->text($qr_text);

// Draw 
$qr->draw('206','254', "../path/to/your/QR_images/folder/test_qr.png");
?>

The above code is pretty self-explanatory. We need to include the class file, then create a object $qr with that class. Next we set the text which will be embedded in the QR image and finally we create the image using draw() method. The draw method takes Width, Height and Image path respectively.

Try it!! It's smooth and perfect.

Multiple record Saving using a loop in CakePHP

Situation :: Suppose, in a sample project, a vendor can have various contacts saved as his reference. We have an array of 10 rows and each of those rows need to be inserted in a database table using a loop. We have a corresponding model "Vendorcontact" where the table name and primary keys have been defined.

Problem :: 
If we use ModelName::save() method inside the loop, it creates a record for the first time in the zeroth iteration of the loop. Next time onwards, it just updates the same record.

Assumption :: 
The array names $vendor_contacts
The related model name is "Vendorcontact"; 
The vendor has an ID 1;
The "Vendorcontact" table has following fields :: vendor_id (INT), vendor_contact (Varchar)

Solution :: 


// Vendor id

$vendor_id = 1;

// Vendor contacts are kept in an Array

$vendor_contacts[0] = "x@x.com";
$vendor_contacts[1] = "xy@xy.com";
...
...
$vendor_contacts[9] = "z@z.com";

// Load corresponding model

$this->loadModel('Vendorcontact');

$a = array(); // 


// Build the loop

for( $i=0; $i < count($vendor_contacts); $i++ )
{
  $a = "";
  $a['vendor_id'] = $vendor_id;
  $a['vendor_contact'] = $vendor_contacts[$i];

  //The important line below tells

  //Cake to INSERT instead of UPDATE 
  $this->Vendorcontact->create(false);  
  $this->Vendorcontact->save( $a );

}

?>