How to use queries in pdo way with laravel

Laravel

Posted on 21 Mar 16 by Vickey
  621



Laravel provide us powerful interface for building SQL queries. We can use a query by using table method.

$myRowQuery = DB::table('users');

Laravel provide other method also 

$userData = DB::first('select * from users where id = 1199');

But in some cases we need to use our row query in pdo way. In laravel we can do this very easily. By getting pdo database connection we can use mysql queries in pdo way. Here are some example

Get pdo database conection

$databaseConection 	= 	DB::connection()->getPdo();
$queryStatement = 	$databaseConection->prepare("SHOW TABLES");
$queryStatement->execute();
$tables 	= $queryStatement->fetchAll();

For fetch data from a table

$tables = 	$queryStatement->fetchAll();
$queryStatement = $databaseConection->prepare("select * from users where email = :email");
$queryStatement->execute(array(':email' => "abc@example.com"));
$row = $queryStatement->fetch();

Insert record in a table

$queryStatement = $databaseConection->prepare("insert into users (email) values (:email)");
$queryStatement->execute(array(':email' => 'abc@example.com'));

 


If this post help you reduce time to develop, you can help me to maintain this website :)
www.000webhost.com