CodeIgniter Forums
problem with query binding - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forum-20.html)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forum-23.html)
+--- Thread: problem with query binding (/thread-53788.html)



problem with query binding - El Forum - 08-09-2012

[eluser]andygo[/eluser]
I am creating an insert query in a model.

I send an associative array of key => value pairs to the model.
(key = field name. value = field value)

I create a list of field names and a list of values and then construct the sql statement....

Eg:
Code:
function insertquery($query_terms, $table)
{

$dsn = $this->session->userdata('dsn');//**btw - is this a security risk?**
$DB1 = $this->load->database($dsn, TRUE);

$fields = '';
$values = '';
$binding = '';

  foreach($query_terms as $key => $value)
  {
   if($value == ''){$values .= "'NULL',";}else{$values .= "'".$value."',";}
  $fields .= $key.",";
  $binding .= '?,';
  }

//remove the last comma
$fields = rtrim($fields,',');
$values = rtrim($values,',');
$binding = rtrim($binding,',');

$sql = "INSERT INTO $table ($fields) VALUES ($binding)";
$DB1->query($sql, array($values));
//echo $DB1->last_query();
}//end method

If I put the $values directly into the sql statement it works fine. If I put the values in the array (as above) it escapes all the single quotes and the sql insert fails....

Could anyone help me out here?
Thanks

EDIT:
Standby ......I think i've sussed it...something to do with the list/array i put in the query()

EDIT2:
from code above....
$values[] = $value;
and
array($values) should just be $values
$DB1->query($sql, $values);