I have now created a generic insertion function using PDO.
To test, I created a table with two fields:
CREATE TABLE `teste`
(
`id` INT NOT NULL AUTO_INCREMENT ,
`nome` VARCHAR(255) NOT NULL ,
`email` VARCHAR(255) NOT NULL ,
PRIMARY KEY (`id`)
);
Html form:
<!DOCTYPE html>
<html>
<head>
<title>Teste Insert PDO Genérico</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<form action="pdo_generico.php" method="post">
Nome: <input type="text" name="nome"><br>
E-mail: <input type="mail" name="email"><br>
<input type="submit" value="Enviar">
</form>
</body>
</html>
pdo_generico.php
<?php
//CONFIG CONEXÃO
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'root';
$password = '';
// CONFIG TABELA E COLUNAS
$tabela = "teste";
// Os tipos podem ser:
// bool, int, str, file, outros(será tratado como str)
$colunas = array(
'nome' => 'str',
'email' => 'str',
);
try
{
$pdo_connection = new PDO($dsn, $user, $password);
} catch(PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
$retorno_do_insert = generic_PDO_insert($pdo_connection, $tabela, $colunas, $_POST);
if($retorno_do_insert)
{
echo 'Dados inseridos com sucesso.';
}
else
{
echo 'Erro.';
}
// =============================================
function generic_PDO_insert($conecta,$tabela,$colunas,$post)
{
$pdo_tipos = array(
'bool' => PDO::PARAM_BOOL,
'int' => PDO::PARAM_INT,
'str' => PDO::PARAM_STR,
'file' => PDO::PARAM_LOB,
'outros'=> PDO::PARAM_STR
);
// Remove os campos que não forem enviados por POST para não criar placeholders para eles
$colunas_existentes = array();
$colunas_arr_key = array();
foreach($colunas as $coluna => $tipo)
{
if(isset($post[$coluna]))
{
$colunas_existentes[$coluna]=$tipo;
$colunas_arr_key[]=$coluna;
}
}
$colunas = $colunas_existentes;
//GERA os PLACEHOLDERS
$colunas_str='';
$placeholders_str='';
$colunas_str = implode(",",$colunas_arr_key);
$placeholders_str = ':'.implode(",:",$colunas_arr_key);
$sql= "INSERT INTO $tabela($colunas_str) VALUES($placeholders_str)";
// echo $sql;
try
{
$query= $conecta->prepare($sql);
foreach ($colunas as $coluna => $tipo)
{
$query->bindValue(":$coluna", $post[$coluna], $pdo_tipos[$tipo]);
}
$query->execute();
return true;
}
catch(Exception $e)
{
return false;
//echo $e->getMessage();
}
}
How about using a cycle to pick them all up until they’re done? Or this
bind_param
is not as it should be and should receive an array of values instead of the values themselves separately.– Jorge B.
Can you show an example with array? So just make a explode in the $values variable
– Rafael Silva
I just understood your question now, I’ll give you an answer.
– Jorge B.
I thought the idea was cool until I saw the table name and the names of the columns passed by POST. I believe that for these 2 it is better to use a string in the code itself rather than go through POST. The size can be dynamically identified by the number of column name posts sent.
– Antonio Alexandre
Mysqli bind with an array of values
– rray
@rray are variable arrays, this does not serve.
– Jorge B.
@Jorgeb. if I understand correctly just unpack (php5.6)
$valores
in$stmt->bind_param()
otherwise only your answer will solve even.– rray
@rray and that’s it, but he says
$valores
may be something other than the example. I also only noticed after Rafael’s comment.– Jorge B.
Test my answer with your table. Any questions ask. Note that the generic_PDO_insert($connects,$table,$columns,$post) function can be used in any script, with an require, left together just to simplify. You can pass $table and $columns for $_POST and clear before moving to the function if you wish, but it is safer to set table name and column array in the script and take only form values.
– Antonio Alexandre