3
I have a function to enter data into the database dynamically. It worked well when running the query
directly using only the function query()
, once I started to restructure the function to work with preparedStatments
, it stopped working. I simply cannot pass these parameters in the method bind_param
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 above, it returns:
Strict Standards: Only variables should be passed by Ference in...
Warning: mysqli_stmt::bind_param(): Number of Elements in type Definition string doesn’t match number of bind variables in...
But if I do it this way:
$vals = implode(',', $valores);
if($prepare->bind_param($type, &$vals)){
$prepare->execute();
}
Returns:
Fatal error: Call-time pass-by-Ference has been Removed in...
Someone knows how to fix this ?
Look at that answer: Select in Mysql with an array
– rray
Thanks for the example, but I did it differently.
– Laura
Creates an answer with the solution:)
– rray
Take a look at these classes: Connectionpdo; Connectionmsi
– KaduAmaral
Hi, thanks for the suggestion, I know it would be easier if I used PDO, but I didn’t want to make much modification to my code.
– Laura