INSERT Query does not work inside a loop

6

So folks, I'm not able to solve this problem of a query inside a foreach loop does not execute. First of all I thought it was something wrong with pdo-> beginTransaction so I commented this part and left pure code only.

    <?php
    if (isset($_POST["nome"])):
        try{
            // Começo da validação
            //$pdo->beginTransaction();
            // Validação do campo nome
            if ($_POST["nome"] != null):
                $procurarnome=$pdo->prepare("SELECT id FROM users WHERE username=$name");
                $procurarnome->execute();
            else:
                die("Houve um erro no sistema, contate um administrador!");
            endif;
            // Validação dos campos dinâmicos
            $cadastraresposta=$pdo->prepare("INSERT INTO form_respostas(perguntaid,username,reposta)VALUES(:perguntaid,$name,:resposta)");
            foreach ($listarpergunta as $pergunta) {
                if ($_POST["pergunta$pergunta->id"] != null):
                    $resposta=addslashes($_POST["pergunta$pergunta->id"]);
                    $cadastraresposta->bindParam(":perguntaid",$pergunta->id,PDO::PARAM_INT);
                    $cadastraresposta->bindParam(":resposta",$resposta);
                    $cadastraresposta->execute();
                    var_dump($cadastraresposta->execute());
                else:
                    $pdo->rollBack();
                    die("Preencha todos os campos corretamente!<br />");
                endif;
            }
            // Todos os arquivos foram preenchidos corretamente
            //$pdo->commit();
            echo "Obrigado!";
        }
        catch(PDOException $pe){
             //$pdo->rollback();
             die($pe->getMessage());
        }
    else:
?>

The INSERT querys inside the foreach do nothing in the database and this var_dump returns me a "boolean false" value. What should I do?

    
asked by anonymous 10.08.2014 / 01:31

3 answers

2

I think you have to fire the bind outside the foreach, try:

$cadastraresposta=$pdo->prepare("INSERT INTO form_respostas(perguntaid,username,reposta)VALUES(:perguntaid,$name,:resposta)");
$cadastraresposta->bindParam(":perguntaid",$perguntaid,PDO::PARAM_INT);
$cadastraresposta->bindParam(":resposta",$resposta);
foreach ($listarpergunta as $pergunta) {
    if ($_POST["pergunta$pergunta->id"] != null):
        $perguntaid=$pergunta->id;
        $resposta=addslashes($_POST["pergunta$pergunta->id"]);
        $cadastraresposta->execute();
    else:
        $pdo->rollBack();
        die("Preencha todos os campos corretamente!<br />");
    endif;
}

PHP Manual:

link

link

    
10.08.2014 / 16:33
1

I see some problems in the code.

  • I do not find it very safe to write bindParam , it might be that PHP uses foreach as variable and continue with the text "- > id".

  • If the array index does not exist in array "pergunta$pergunta->id" a call returns $pergunta ?

  • Suggestions:

  • Accept Jader's suggestion;

  • Use another variable to bind the question id. It may not be necessary, but it seems simpler to me;

  • Rewrite the indexes of $_POST as null or something similar, which can be more reliable;

  • Wow, I did not even know that $_POST could be written like this. Is not traditional more readable and more supported by code editors?

  • I think that when using bind, strings do not need to be dealt with addslashes, however you should test this part because I'm not sure;

  • Check the variable "pergunta${perguntaId}" ;

  • I particularly like to initialize the variables before use;

  • Jader noted the lack of string delimiters in the query, replacing it with if .

  • The part in question of the code would look like this:

    // Validação dos campos dinâmicos
    $cadastraresposta=$pdo->prepare("INSERT INTO form_respostas (perguntaid, username, reposta) VALUES (:perguntaid, '$name', :resposta)");
    $perguntaId = 0;
    $resposta = 0;
    $cadastraresposta->bindParam(":perguntaid", $perguntaId, PDO::PARAM_INT);
    $cadastraresposta->bindParam(":resposta", $resposta);
    foreach ($listarpergunta as $pergunta) {
      $perguntaId = $pergunta->id;
      $resposta = $_POST["pergunta${perguntaId}"];
      if ($resposta != null) {
        $cadastraresposta->execute();
        if ($cadastraresposta->errorCode() != 0) {
          print_r($cadastraresposta->errorInfo());
          die("Erro ao executar Query!");
        }
      } else {
        $pdo->rollBack();
        die("Preencha todos os campos corretamente!<br />");
      }
    }
    // Todos os arquivos foram preenchidos corretamente
    //$pdo->commit();
    echo "Obrigado!";
    

    If it does not work, try to see what's wrong with null or $name .

        
    10.08.2014 / 21:54
    -2

    The post is old but should help in the future; The solution is to use bindValue instead of bindParam.

        
    09.09.2016 / 06:02