Jump to content

PHP MYSQL and Checkboxes problems...


oolongdavies

Recommended Posts

I am trying to add records to a database based on a session variable called $_SESSION['user_id'] and checkbox values selected by the user.

 

I think I need to store the data in an array and then somehow manipulate so that it can be inserted into a row in the db.

 

I also have a feeling that I will have to cycle through the array elements and store each value in a dynamically created variable so that it can be inserted.

 

 

So, does anybody know how I can achieve this?

 

btw, the page posts to itself

here's my code:

 

<?php
if ($_POST['submit'] == 'submit') {

$sql='INSERT INTO mytable (fld_user, fld_cboxvalue) VALUES '. $_SESSION['user_id'] .' ,"' .$_POST['risks'] .'")';
 mysql_query($sql) or die(mysql_error());
 header('location: mypage.php');
}
?>
<form name = "risks" method="post">
  

<input type="checkbox" name="risks" value="R00" >R00<br>
<input type="checkbox" name="risks" value="R01" >R01<br>
<input type="checkbox" name="risks" value="R02" >R02<br>
<input type="checkbox" name="risks" value="R03" >R03<br>
<input type="submit"  value="submit" name="submit">

</form>

Thanks in advance,

 

J

Link to comment
https://forums.phpfreaks.com/topic/52339-php-mysql-and-checkboxes-problems/
Share on other sites

To insert it as an array into the database use this:

 

<?php

if ($_POST['submit'] == 'submit') {

 

$sql='INSERT INTO mytable (fld_user, fld_cboxvalue) VALUES '. $_SESSION['user_id'] .' ,"' .implode("|", $_POST['risks']).'")';

mysql_query($sql) or die(mysql_error());

header('location: mypage.php');

}

?>

<form name = "risks" method="post">

 

<input type="checkbox" name="risks[]" value="R00" >R00<br>

<input type="checkbox" name="risks[]" value="R01" >R01<br>

<input type="checkbox" name="risks[]" value="R02" >R02<br>

<input type="checkbox" name="risks[]" value="R03" >R03<br>

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

 

</form>

 

This will put each 'risk' in the database seperated by a "|". If you want to seperate them with something else (perhaps a comma and a space) then change implode("|", $_POST to implode(", ", $_POST

When you want to show them, you will have to explode the array or just echo the field.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.