1

I have written the below to read in data from a radio button (var1) and some checkboxes (var2)

   require('config.php');

  $con = mysql_connect("localhost", $db_username, $db_password);
    if (!$con)
    {
      die('Could not connect: ' . mysql_error());
    }
    mysql_select_db($db_name, $con);

  $var1 = $_GET['var1'];
  $var1 = mysql_real_escape_string( $var1 );
  $var2 = $_GET['var2'];
  $var2 = mysql_real_escape_string( $var2 );  

  $running_total = 0;
  $last_update = "SELECT * FROM $db_tablename ORDER BY id DESC LIMIT 1";
  $result = mysql_query($last_update);

 $insert_query = "INSERT INTO $db_tablename (var1, var2) ";
  $insert_query .= sprintf( "VALUES('%s', '%s')", $var1, $var2);

  $insert_result = mysql_query($insert_query);
  if(!$insert_result) {
    die('insert query failed' . mysql_error());
  }

  mysql_close($con)

The input html looks like...

<input type="radio" name="var1" value="value1">Test 1</input>
<input type="radio" name="var1" value="value2">Test 2</input>
<input type="radio" name="var1" value="value3">Test 3</input>
<input type="radio" name="var1" value="value4">Test 4</input>

<input type="checkbox" name="var2" value="checkbox1">CB 1</input>
<input type="checkbox" name="var2" value="checkbox2">CB 1</input>
<input type="checkbox" name="var2" value="checkbox3">CB 1</input>
<input type="checkbox" name="var2" value="checkbox4">CB 1</input>

Everything works as expected and but as var2 allows for multiple checkboxes to be selected I would like to save multiple values. I realise I need to do this as an array but I cant work it out.

Can anyone help or have a solution or example they can point me to?

0

3 Answers 3

2

it would be var2[] as the name and view the results as

foreach($_POST['var2'] as $checkedItem)
{
    echo $checkedItem;
}
Sign up to request clarification or add additional context in comments.

Comments

1

The html: `

<input type="radio" name="var1" value="value1">Test 1</input>
<input type="radio" name="var1" value="value2">Test 2</input>

<input type="checkbox" name="var2[]" value="check" /> CB 1
<input type="checkbox" name="var2[]" value="check" /> CB 2

`

and the SQL :

Array $_POST['var2'] contains the checkboxes.

Comments

0

Change the name of var1 to "var1[]", and change the name of var2 to "var2[]"...

 $var1 = $_GET['var1'];
 $var2 = $_GET['var2'];
 echo count($var1);
 echo count($var2);

Gl mf

1 Comment

the radio buttons (var1) dont need to have the [] as its only a single value

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.