Monday, September 22, 2014

Started with variables ends with Parameters

Stranger asked like this

How can I assign PHP variables to multiple columns?

 "SELECT a,b,c FROM ant WHERE a='$a' AND b='$b' AND c='$c' ");


Anonymous 1:
started like this
Use PDO (PHP Database Object) . Its the latest way to bind variables with a sql query .
<?php

/* Execute a prepared statement by binding PHP variables */
$value_a  = "value of a";
$value_b  = "value of b";
$value_c  = "value of c";
$sth = $dbh->prepare("SELECT a,b,c FROM ant WHERE a=? AND b=? AND c= ? ");
$sth->bindValue(1, $value_a, PDO::PARAM_STR);
$sth->bindValue(2, $value_b, PDO::PARAM_STR);
$sth->bindValue(3, $value_c, PDO::PARAM_STR);
$sth->execute();

?>

Anan 2:
 As a standard practice, NEVER generate query by string catenation.
Fairly bad idea.
Instead do this:

$format_query = "SELECT a,b,c FROM some_table
              WHERE   a='%s' AND   b='%s' AND   c='%s' " ;
$query = sprintf($format_query, $a,$b,$c);
# for debug
echo "<br/>" .  $query . "<br/>";

Let us know if that helped.

Anon 3:
Query="Select a,b,c FROM ant WHERE a='".$a."' AND b='".$b."' AND c='".$c."' ";
Remember string concentration


Anon 4:
My recommendations:
ditch mysqli in favor of PDO (with mysql driver)
use PDO paremeterized prepared statements
You can then do something like:

$pdo_obj = new PDO( 'mysql:server=localhost; dbname=mydatabase',                      $dbusername, $dbpassword );

 $sql = 'SELECT column FROM table WHERE condition=:condition';

$params = array( ':condition' => 1 );

$statement = $pdo_obj->prepare( $sql,    
array( PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY ) );

$statement->execute( $params );

$result = $statement->fetchAll( PDO::FETCH_ASSOC );


PROs:
No more manual escaping since PDO does it all for you!
It's relatively easy to switch database back-ends all of a sudden.

From my Opinion/Experience
PDO will help to avoid SQL Injection.
PDO supports various databases.
PDO makes migration easier between different databases.
PDO will fasten your query execution time.

CONs:
I Cannot think of any.

No comments:

Post a Comment