INSERT with prepare does not work

2

I'm trying to insert data into the database using mysqli prepare but are not inserting the data, and does not show any error

Questions :::

  • What am I doing wrong in this code below?
  • Is this the best way to do it?
  • Could you put an example?

    $conecta = new mysqli($hostname, $username, $password, $dbdatabase);
    if($conecta->connect_error){
    echo "Conexao:<span class=\"ls-tag-danger\">Erro!</span>";
    }else{ 
    echo "Conexao:<span class=\"ls-tag-success\">OK!</span>";
    }
    
    
    $sql = $conecta->prepare("INSERT INTO cotacao (chave,id_transfer,id_empresa,nome) 
    VALUES (?,?,?,?)");  
    $sql->bind_param('s', $chave,$id_transfer,$idc,$nome); //    
    $sql->execute();
    $sql->close();
    $conecta->close();
    

Thank you

    
asked by anonymous 27.05.2017 / 15:16

3 answers

1

The error happens in your bind_param method, the method tells SQL what type of data is being sent to the query, and there must be one for each parameter that you send in the bind. The s means that the data is of type string, i integer, d double and b blob.

 $sql = $conecta->prepare("INSERT INTO cotacao (chave,id_transfer,id_empresa,nome) 
    VALUES (?,?,?,?)");  
    $sql->bind_param('iiis', $chave,$id_transfer,$idc,$nome); //Supondo que a chave é um integer, se não ela também recebe um "s" de string    
    $sql->execute();
    $sql->close();
    $conecta->close();
    
27.05.2017 / 15:37
1

The bind_param that is wrong / or missing , for each item you must have your defined type, example in your code:

$sql = $conecta->prepare("INSERT INTO cotacao (chave,id_transfer,id_empresa,nome) 
VALUES (?,?,?,?)");  
$sql->bind_param('iiis', $chave,$id_transfer,$idc,$nome);

That is, the statement of the other types was missing in the are 4.

The types are:

+-----+-------------------------------------------------------------------------------+
|  i  | corresponde a uma variável de tipo inteiro                                    |
+-----+-------------------------------------------------------------------------------+
|  d  | corresponde a uma variável de tipo double                                     |
+-----+-------------------------------------------------------------------------------+
|  s  | corresponde a uma variável de tipo string                                     |
+-----+-------------------------------------------------------------------------------+
|  b  | corresponde a uma variável que contém dados para um blob e enviará em pacotes |
+-----+-------------------------------------------------------------------------------+
    
27.05.2017 / 15:38
0
$sql = "INSERT INTO cotacao SET chave = ?, id_transfer = ?, id_empresa = ?, nome = ?";
$query = $mysqli->query($sql);

Do not forget to pass the array parameters, or use normal ones yourself.

    
27.05.2017 / 15:21