SQLSTATE[HY093] error: Invalid Parameter number: Parameter was not defined,

Asked

Viewed 1,168 times

0

I am having a problem for some time with a registration done in ajax but when trying to register client user in the client table an sql error stating that a parameter is missing

I have tried several ways. I understand that this parameter that the query wants is the table id ,which is sent in the array index 0 $dados, how can I make the index 0 not be included in the query?

I’m sending my entire code to see if anyone can help me connection this ok, ajax is ok the problem is on the crud.php page.

$(function(){
    //GERAIS
    var errmsg  = $('.msg');
    var forms   = $('form');
    var botao   = $('.j_buttom');
    var urlpost = 'php/crud.php';

    botao.attr("type","submit");

    forms.submit(function(){
        errmsg.fadeOut("fast");
        return false;
    });

    function carregando(){
        errmsg.empty().html('<p class="load"><img src="img/load.gif" alt="Carregando..."> Aguarde, enviando requisição!</p>').fadeIn("fast");
    }

    function errosend(){
        errmsg.empty().html('<p class="erro"><strong>Erro inesperado,</strong> Favor contate o admin!</p>').fadeIn("fast");
    }

    //GENÉRICAS
    function errdados( mensagem ){
        errmsg.empty().html('<p class="erro">'+mensagem+'</p>').fadeIn("fast");
    }

    function sucesso( mensagem ){
        errmsg.empty().html('<p class="accept">'+mensagem+'</p>').fadeIn("fast");
    }

    $.ajaxSetup({
        url:    urlpost,
        type:   'POST',
        beforeSend: carregando,
        error:      errosend
    });

    //CADASTRO
    var cadastro = $('form[name="cadastro"');

    cadastro.submit(function(){
        var dados = $(this).serialize();
        var acao = "&acao=cadastro";
        var sender  = dados+acao;

        $.ajax({
            data:   sender,
            success: function( resposta ){
                    if(resposta == '1'){
                    errdados('<strong>Erro ao cadastrar:</strong> Existem campos em branco!');
                }else if(resposta == '2'){
                    errosend();
                }else{
                    sucesso( 'Parabéns <strong>'+resposta+'</strong>, seu cadastro foi realizado!' );
                }               
            },

        });
    });

}); 

Connection to the database

function conectar() {
    define("HOST", "localhost");
    define("BD", "db_clientes");
    define("USER", "root");
    define("PASS", "");

    try {
        $dsn = "mysql:host=".HOST.";dbname=".BD;
        $pdo = new PDO($dsn, USER, PASS);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    } catch (PDOException $e) {
        echo "Erro: ".$e->getMessage();
    }

    return $pdo;
}

require 'conexao.php';

switch ($_POST['acao']) {
  case 'cadastro':

    $c['nome'] = strip_tags(trim($_POST['nome']));
    $c['sobrenome'] = strip_tags(trim($_POST['sobrenome']));
    $c['email'] = filter_var($_POST["email"], FILTER_VALIDATE_EMAIL);
    $c['telefone'] = filter_var($_POST["telefone"], FILTER_VALIDATE_INT);
    $c['senha'] = strip_tags(trim($_POST['senha']));
    $c['data_cadastro'] = date('Y-m-d H:i:s');
    if (in_array('', $c)) {
      echo '1';
    } else {

      $dados = array(
        1 => $c['nome'],
        2 => $c['sobrenome'],
        3 => $c['email'],
        4 => $c['telefone'],
        5 => $c['senha'],
        6 => $c['data_cadastro'],

      );

      $Fields = implode(',  ', array_keys($c));
      $values = ':'.implode(' , :', array_keys($c));
      try {

        $cadastra = conectar()->prepare("INSERT INTO clientes  ({$Fields})  VALUES ({$values})");
        $cadastra->execute($dados);

        if ($cadastrar->rowCount() == 1) {
          echo $c['nome'].' '.$c['sobrenome'];
        } else {
          echo '2';
        }
      } catch (PDOException $e) {
        echo $e->getMessage();
      }
    }
    break;
  default:
    echo 'Erro ao selecionar ação!';
}
  • You are passing the values in the query in the form :name, :email and etc. To use this in PDO, you must use bindValue and not pass array in the execute method. See this link : http://php.net/manual/en/pdostatement.bindvalue.php You can use Pdobindarray($cadastra,$data); and then call execute without passing parameters

1 answer

0

Your error is in passing data array:

$dados = array(
   1 => $c['nome'],
   2 => $c['sobrenome'],
   3 => $c['email'],
   4 => $c['telefone'],
   5 => $c['senha'],
   6 => $c['data_cadastro'],
);

Just change to:

$dados = array(
  ":nome" => $c['nome'],
  ":sobrenome" => $c['sobrenome'],
  ":email" => $c['email'],
  ":telefone" => $c['telefone'],
  ":senha" => $c['senha'],
  ":data_cadastro" => $c['data_cadastro'],
);

See working:

inserir a descrição da imagem aqui

Obs, be careful with the line

$cadastra->execute($dados);
if ($cadastrar->rowCount() == 1) {

$cadastra and not $cadastrar

  • thanks seems such a simple thing and I 8 grating Aki!!

  • Because he said to be careful , I’m starting now in php and need refencia , all advice is welcome :)

  • thanks for that hug, I was very frustrated with that mistake because I tried a lot of things.

Browser other questions tagged

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