Insert into seat with function

Asked

Viewed 432 times

2

I’m trying to make an entry in the database using a function but I’m not able to enter the respective values;

HTML:

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

where submitTextois a send 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());
}
}

Upshot:

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

  • 1

    Paste this into your function, so we can test if the posts are coming. foreach($_POST as $key=>$val){ $dados[$key] = $val; } echo "<pre>"; print_r($data); echo "<pre>"; die();

  • Print sql, in this Insert only has number? as it is needs to escape the strings with simple quotes. Call $inserir->execute() once.

3 answers

1


You can draw up this way a foreach(), to search all fields posted and enter in the database:

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

Thus, the name of the database field should be the same as the name of the field.

  • 1

    I understood what you explained André, thank you very much! I used $campo[] = $key;&#xA; $valor[] = "'$val'";&#xA; &#xA; $campos = implode(",", $campo);&#xA; $valores = implode(',', $valor); to make it easier for me to understand in the future.

1

It is possible to simplify logic and uses Prepared statements, first check how many placeholders(queries) will need this number is based on the amount of values passed in $dados, play placeholders in sql and finally bind the values with the 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());
    }
}

0

Unless there are only numbers, and floating point numbers are converted to point string, the instruction must fail.

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

You are not using prepare’s value assignment, which is the biggest advantage, because it treats string limitation with quotation marks, numbers, etc. If you are going to use it this way, it is best to run directly with $con->query($query); at once.

I recommend rebuilding to use prepare values treatment.

http://php.net/manual/en/pdo.prepared-statements.php http://php.net/manual/en/pdo.prepare.php

Browser other questions tagged

You are not signed in. Login or sign up in order to post.