Tuesday, 15 June 2010

Mysql dynamic sql statement with PDO and parameters -



Mysql dynamic sql statement with PDO and parameters -

i want create dynamic sql statement , run using pdo. problem have parameters , cannot think of way pass parameters. ex :

$query = "select * tbl_task 1=1"; if (!empty($name)) $query .= " , name = ?"; if (!empty($status)) $query .= " , status = ?" $db_stmt = new pdostatement(); $db_stmt = $this->db->prepare($query); $db_stmt->bindparam (1,$name); $db_stmt->bindparam (2,$status);

my parameters not binded , don't know how many parameters have bind, unless write same if statements bindparam instructions.

i tryed mysql_real_escape_string instead bindparam pdo reason parameters added empty.

any thought on how can build dynamic query , bind parameters pdo ?

edit 1 :

$arr = array(); if (!empty($name)){ $query .= " , `name` :name"; $arr['name'] = $name; } $db_stmt = new pdostatement(); $db_stmt = $this->db->prepare($query); $db_stmt->execute($arr);

how can write "like" statement ? tried

$query .= " , `name` :name" . "%";

and not working.

what following:

$query = "select * `tbl_task` 1=1"; $arr = array(); if (!empty($name)) { $query .= " , `name` = :name"; $arr['name'] = $name; } if (!empty($status)) { $query .= " , `status` = :status"; $arr['status'] = $status; } $this->db->begintransaction(); seek { $tmp = $this->db->prepare($query); $tmp->execute($arr); $this->db->commit(); } catch(pdoexception $ex) { $this->db->rollback(); $this->log->error($ex->getmessage()); }

mysql pdo dynamic-sql

No comments:

Post a Comment