Insert into bank with function

2

I'm trying to make an insert into the database using a function but I'm not able to enter its values;

HTML:

<?php if (isset($_POST['submitTexto'])) {
                    inserir('empresa', $_POST);
                } ?>

where submitTexto is a submit button.

Function:

<?php 

function conectar() {
try {
    $pdo = new PDO("mysql:host=localhost;dbname=fap", "root", "");
}
catch(PDOException $e) {
    echo $e->getMessage();
}
return $pdo;
}

conectar();

function inserir($tabela, $dados) {
$con = conectar();
foreach ($dados as $dado => $valores) {
    $campo = array();
    array_push($campo, $dado);

    $valor = array();
    array_push($valor, $valores);

}
$campo = implode(',', $campo);
$valor = implode(',', $valor);

$inserir = $con->prepare("INSERT INTO $tabela($campo) VALUES($valor)");
$inserir->execute();
if ($inserir->execute()){
    echo "Inserido com sucesso!";
}
else {
    echo "Erro!";
    print_r($con->errorInfo());
}
}

Outcome:

  

Error! Array ([0] = > 00000 [1] = > [2] = >)

    
asked by anonymous 10.08.2015 / 16:29

3 answers

1

You can create a foreach() in this way so that you search for all the fields you have posted and enter in the database:

  foreach($_POST as $key=>$val){
        $dados[$key] = $val;
        $campos = implode(",", $key); 
        unset($_POST["submitTexto"]);  
   }

In this way, the name of the database field should be the same as the name of the field.

    
10.08.2015 / 16:52
1

It is possible to simplify logic and use prepared statements, first check how many placeholders this number will be based on the amount of values passed in $dados , throw placeholders in sql, and finally bind values with columns, just pass an array in execute() with the values.

function inserir($tabela, $dados) {
    $campos = implode(", ", array_keys($dados));
    $values = implode(", ", array_values($dados));

    $totalInterrogacoes = count($dados);

    $interrogacoes = str_repeat('?,', $totalInterrogacoes);
    $interrogacoes = substr($interrogacoes, 0, -1); // remove a última virgula

    $sql = "INSERT INTO $tabela($campos) VALUES($interrogacoes)";

    $con = conectar();
    $inserir = $con->prepare($sql);

    if($inserir->execute($values)){
       echo 'sucesso';
    }else{
        print_r($con->errorInfo());
    }
}
    
10.08.2015 / 17:09
0

Unless you have only numbers, and floating-point numbers are converted to a dotted string, the statement should fail.

As you are using prepare, to see the error, use print_r($inserir->errorInfo()); to see the correct error.

You are not using the value assignment of prepare, which is the biggest advantage, because it treats the limitation of strings with quotes, numbers, etc. If it is to be used this way, it is best to run directly with $con->query($query); at a time.

I recommend rebuilding to use the prepare value processing.

link link

    
10.08.2015 / 16:41