I'm having some real difficulties with my code here. I'm trying to pass an array of data to a function and have it dynamically build a INSERT statement using prepared statements.
So I have this:
public function create($data) {
global $mysqli;
foreach ($data as $field => $value) {
$fields[] = $field;
$values[] = $value;
}
$query = "INSERT INTO " . $this->class_name . " (";
for ($i = 0; $i < count($fields); $i++) {
if ($i == (count($fields) - 1)) {
$query .= "" . $fields[$i] . "";
} else {
$query .= "" . $fields[$i] . ", ";
}
}
$query .= ") VALUES (";
$params = array();
for ($i = 0; $i < count($values); $i++) {
if (is_int($values[$i])) {
$params[] = "i";
} else {
$params[]= "s";
}
if ($i == (count($values) - 1)) {
$query .= "?";
} else {
$query .= "?, ";
}
}
$query .= ")";
if ($stmt = $mysqli->prepare($query)) {
call_user_func_array(array($stmt, "bind_param"), array_merge($params, $values));
} else {
die("COULD NOT CONNECT create()");
}
//echo $query;
}
The issues is I keep getting the following error:
Warning: Parameter 2 to mysqli_stmt::bind_param() expected to be a reference, value given in E:\xampp2\htdocs\school2\application\models\CRUDAObject.php on line 44
I'm pretty new to prepared statements, but I can't work out which format/layout the array needs to be when I pass it.
Can anyone help?