PHP - Return reference -
i m trying create function take array , create columns , values don't know how return references functions. appreciated.
private function data($data) { $columns = ""; $values = array(); foreach ($data $column => $value) { $columns .= ($columns == '') ? '' : ', '; $columns .= $column; $values[$column] = &$data[$column]; } return array($columns, $values); }
this function inserts data in database.
/** * insert item items table. * * @param (array) $data - column => value array created in item class. */ public function insertitem($data) { $columns = ""; $values = array(); $prep = "isiisiisiiis"; /*foreach ($data $column => $value) { $columns .= ($columns == '') ? '' : ', '; $columns .= $column; $values[$column] = &$data[$column]; }*/ $thedata = $this->data($data); $a = str_repeat('?, ', count($data) ); $b = substr_replace($a, '', -2); $q = $this->db->mysqli->prepare("insert items ($columns) values ($b)"); call_user_func_array( array($q, 'bind_param'), array_merge(array($prep), $values) ); $q->execute(); $q->close(); //return id return $this->db->mysqli->insert_id; }
edit ** working code:
private function data(&$data) { $columns = ""; $values = array(); foreach ($data $column => $value) { $columns .= ($columns == '') ? '' : ', '; $columns .= $column; $values[$column] = &$data[$column]; } return array($columns, $values); }
and accessing this:
$thedata = $this->data($data); $thedata[0]; //$columns $thedata[1]; //$values
try this: add &
in function param , remove &
inside foreach loop.
private function data (&$data) { $columns = ""; $values = array (); foreach ($data $column => $value) { $columns .= ($columns == '') ? '' : ', '; $columns .= $column; $values[$column] = $data[$column]; } return array ($columns, $values); }
inside public function insertitem remove $thedata =
public function insertitem ($data) { [..] $this->data ($data); }
Comments
Post a Comment