Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP multiple checkbox to database

hello i have been trying to use multiple checkboxes to input info to a db i used [] with checkbox name but "array" is saved to db. What code and where should i input for this to work correctly? thank you!

this is my form code:

<?php
require_once('connection.php');

if(isset($_GET['process']))

    {
    $query = "Insert INTO `lista_precios` (Marca) values('$_POST[Marca]')";
    //echo $query; exit;
    $result = mysql_query($query) or die(mysql_error());
    if(!$result)
    {
       $msg = "not Inserted";
       }
       else
       {
       $msg = "Inserted";
       header("location:form.php?m=".$msg);
    }
   }
?>

<method="post" action="form.php?process">
<p>MARCA: <br><br>
<input type="checkbox" name="Marca" value="ACER">ACER     
<input type="checkbox" name="Marca" value="AOC">AOC 
<input type="checkbox" name="Marca" value="APPLE">APPLE

<input type="submit" name="Submit" value="Submit" />


</form>

And this is my connection:

<?php


$link=mysql_connect("xxxx","xxxx","xxxx");
  $database='xxxxxxx';             
  if (!$link)
  die('Failed to connect to Server'.mysql_error());
  $db=mysql_select_db($database, $link);
  session_start();
  if(!$db)
  die('Failed to select Data Base '.mysql_error());


?>
like image 245
user3610477 Avatar asked Jul 13 '26 08:07

user3610477


1 Answers

First off you need to set your checkboxes names and turn them to name=Marca[]

<form method="post" action="form.php?process">
    <p>MARCA: <br><br>
    <input type="checkbox" name="Marca[]" value="ACER">ACER
    <input type="checkbox" name="Marca[]" value="AOC">AOC
    <input type="checkbox" name="Marca[]" value="APPLE">APPLE

    <input type="submit" name="Submit" value="Submit" />
</form>

Then on your form.php process the values:

Note: You have to understand, you can't just put $_POST['Marca'] and concatenate them into the string, you have to get each value and build the insert query.

if(isset($_GET['process'])) {
    $marca = isset($_POST['Marca']) ? $_POST['Marca'] : null;
    if(count($marca) < 3) {
        // your validation that no checkboxes were selected
        $msg = 'You need to select at least 3 values';
        header("Location: form.php?m=".$msg);
    }

    $values = implode(',', $marca);
    $statement = "INSERT INTO `lista_precios` (`Marca`) VALUES ('$values');";
    // should result into
    // INSERT INTO `lista_precios` (`Marca`) VALUES ('ACER,AOC,APPLE');
    // then continue on your query code
    $query = mysql_query($statement);
    $msg = ($query && mysql_affected_rows() > 0) ? 'Inserted' : 'Not Inserted';
    header("Location: form.php?m=".$msg);
}
like image 67
user1978142 Avatar answered Jul 15 '26 01:07

user1978142



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!