I have a function to insert data into the database dynamically. It worked fine when running query
directly using only the query()
function, so I started to restructure the function to work with preparedStatments
, it stopped working. I simply can not pass these parameters to the bind_param
method since the values are dynamic.
<?php
$mysqli = new mysqli('localhost','root','','loja_teste');
function insert($tabela, $args = []){
global $mysqli;
$campos = implode(', ', array_keys($args));
$valores = array_values($args);
# achar os tipos, dinamicamente;
$type = $binds = "";
$i = 1;
foreach($valores as $valor){
switch(gettype($valor)){
case 'integer':
$type .= 'i';
break;
case 'string';
$type .= 's';
break;
default:
$type .= 's';
break;
}
$binds .= "?";
if($i < count($valores)){
$binds .= ", ";
}
$i++;
}
$sql = "INSERT INTO {$tabela} ({$campos}) VALUES ({$binds})";
if($prepare = $mysqli->prepare($sql)){
# Aqui onde retorna o erro
if($prepare->bind_param($type, implode(',', $valores))){
$prepare->execute();
} else {
die($mysqli->error);
}
} else {
die($mysqli->error);
}
}
var_dump(insert('tabela', ['nome'=>'Anel de Ouro','preco'=>1000]));
?>
With the function from above, it returns:
Strict Standards: Only variables should be passed by reference in ...
Warning: mysqli_stmt :: bind_param (): Number of elements in type definition string does not match number of bind variables in ...
But if I do it this way:
$vals = implode(',', $valores);
if($prepare->bind_param($type, &$vals)){
$prepare->execute();
}
Return:
Fatal error: Call-time pass-by-reference has been removed in ...
Does anyone know how to solve this?