How to Write Product Checkbox and Id to Mysql

Asked

Viewed 196 times

1

I’m trying to record some checkbox plus the ID product in my database MySQL but I’m not getting it, what I have so far is this:

The form:

<input class="chk" type="checkbox" name="cores[]" value="<?php echo $row_RsCores['id_cor_textura']; ?>" />
<input name="IdProduto" type="hidden" value="<?php echo $id_produto; ?>">

The script that should perform the recording:

// RESGATE DAS VARIÁVEIS
$IdProduto = $_POST['IdProduto'];
$itens = $_REQUEST['cores'];

if (!empty($itens)) {                
    $qtd = count($itens);
    for ($i = 0; $i < $qtd; $i++) {
        // echo $itens[$i];//imprime o item corrente

        mysql_select_db($database_conexao, $conexao);
        $query = "INSERT INTO produto_textura  
            (id_produto,
            id_cor_textura
            ) 
            VALUES 
            ('$IdProduto',
            '$itens[$i]')";
     }

   $queryExec = mysql_query($query, $conexao) or die( "Erro ao inserir checks no banco de dados.");
}

The error that occurs is this:

"Erro ao inserir checks no banco de dados."

Man MySQL is like this:

inserir a descrição da imagem aqui

  • ve what error is wrong? $queryExec = mysql_query($query, $connected) or die('Invalid query: ' . mysql_error());

  • Hello @Marcelodiniz, I just appeared "1" and is being sent to the bank only the last record.

  • Is it always the same product id(that Hidden input)? and mysql_select_db must be out of for. Another test you can do is to print the generated sqls and run them all in the database at once.

  • Hello $rray, yes the product will be inserted only once and I gave an echo to show the generated sql and it just shows me the last record of 4 I’m trying to iserir.

2 answers

1

The columns id_produto and id_cor_textura are of type int and you are trying to insert values of type string. Besides, you’re trying to insert "$IdProduto" instead of the variable value IdProduto.

Change the query to insert values with correct types and correct references:

$query = "INSERT INTO produto_textura  
            (id_produto,
            id_cor_textura
            ) 
            VALUES 
            ($IdProduto,
            $itens[$i])";

If it doesn’t work, change the query result to show the query execution error:

$queryExec = mysql_query($query, $conexao) or die( "Erro ao inserir registro no  banco de dados: ".mysql_error());
  • I didn’t quite understand what you meant: "Also, you’re trying to enter "$Idproduct" instead of the value of the Idproduct variable." The $Idproduct variable in the query has the value rescued from my Idproduct from my form.

1


The last record is inserted because the value of $query is reactivated every time around the is, ie the mysql_query() must be inside the for to enter N records.

Look at the problem:

for ($i = 0; $i < $qtd; $i++) {
        $query = "INSERT INTO produto_textura  
            (id_produto,
            id_cor_textura
            ) 
            VALUES 
            ('$IdProduto',
            '$itens[$i]')";
} // <--- fim do for

//apenas o último valor dentro de $query será inserido.
$queryExec = mysql_query($query, $conexao) or die( "Erro ao inserir checks no banco de dados.");

It is possible to make some simplifications, such as mounting an Insert template with N values so only one query is sent to the bank. Remove the mysql_select_db() from inside the for.

mysql_select_db($database_connected, $connected);

$IdProduto = $_POST['IdProduto'];
$itens = $_REQUEST['cores'];

if (!empty($itens)) {
    $query = "INSERT INTO produto_textura (id_produto, id_cor_textura) VALUES ";                
    foreach($itens as $item){
        $query .= sprintf("('%s','%s'),", $IdProduto, $item);
    }
    $query = trim(',', $query);
    $queryExec = mysql_query($query, $conexao) or die(mysql_error());
}
  • Thanks @rray, I was sure I was making a mistake childish but could not see the problem, again thank you.

  • @adventistapr, what is the sql error?

  • Hello @rray, the error that was occurring was this: "Error inserting checks into database." but the same was happening because the initial logic was with a programming failure. Thanks for the excellent code completing your reply, excellent.

Browser other questions tagged

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