Hi,
Iam new to PHP I need some help I am trying to insert multiple checkboxes values
<td>
<input name="myvar[]" type="checkbox" value="abc">
abc<br/>
<input name="myvar[]" type="checkbox" value="def">
def<br>
<input name="myvar[]" type="checkbox" value="ghi">
ghi</td>
along with other datas to the database, and I dont know how to do this
I wrote query for inserting other datas to db,(but i dont know how to include the loop value from the checkbox along with this).
$Details=mysql_query("insert into Example values('$ID','$data1','$data2'......) please explain I am new in this field

Dani AI

Generated

Quick summary and improvement notes for and : the approach of submitting checkbox values as an array and creating one row per selected item is fine conceptually, but the thread uses old mysql_* calls and per-row string concatenation (risk: SQL injection, performance, maintainability). Two patterns work well today — a normalized junction table (recommended) or storing the selection as JSON in one column (simpler, but less queryable). Below are concise, practical examples and a short checklist.

Suggested schema (junction table)

CREATE TABLE persons (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100));
CREATE TABLE sports  (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) UNIQUE);
CREATE TABLE person_sports (
  person_id INT NOT NULL,
  sport_id  INT NOT NULL,
  PRIMARY KEY(person_id, sport_id),
  FOREIGN KEY(person_id) REFERENCES persons(id),
  FOREIGN KEY(sport_id)  REFERENCES sports(id)
);

Insert multiple selections safely (PDO + single multi-value INSERT)

$selected = $_POST['myvar'] ?? []; // array of sport IDs or names
// build "(?,?),(?,?)" placeholders and flattened params: [personId, sport1, personId, sport2, ...]
$placeholders = array_fill(0, count($selected), '(?,?)');
$sql = 'INSERT INTO person_sports (person_id,sport_id) VALUES ' . implode(',', $placeholders);
$params = [];
foreach ($selected as $s) { $params[] = $personId; $params[] = (int)$s; }
$pdo->beginTransaction();
$pdo->prepare($sql)->execute($params);
$pdo->commit();

Alternative: store selection as JSON (single column)

$pdo->prepare('UPDATE persons SET sports_json = ? WHERE id = ?')
    ->execute([json_encode($selected), $personId]);

Quick checklist and gotchas

  • Always validate that the POST value exists and is an array.
  • Use prepared statements or parameterized queries; avoid mysql_* functions.
  • Add a UNIQUE constraint on the junction table primary key to prevent duplicates; use transactions for reliability.
  • If you need to display checked boxes on load, decode the stored array/JSON and test membership when rendering.
    These changes keep the design scalable, secure, and easy to query.

Recommended Answers

All 3 Replies

assuming you had:

<input type="text" name="person" value="John"/>
<input name="sport[]" type="checkbox" value="baseball">
<input name="sport[]" type="checkbox" value="basquetball">
<input name="sport[]" type="checkbox" value="football">
<input name="sport[]" type="checkbox" value="hocket">

then:

foreach($_POST['sport'] as $value)
{
  $sql = sprintf("INSERT INTO `Atletes`(`personId`,`sportName`) VALUES('%s','%s')"
                ,mysql_real_escape_string($_POST['person'])
                ,mysql_real_escape_string($value)
                );
}

thanks heilo,I was able to insert the values, and it will take different rows in the database right?like baseball in one row then basketball in the second row.... and will you please help me in displaying the value from the database too,

it will take different rows in the database right?like baseball in one row then basketball in the second row

correct

but this might be better:

<input name="sport[3][]" type="checkbox" value="baseball">
<input name="sport[3][]" type="checkbox" value="basquetball">
<input name="sport[3][]" type="checkbox" value="football">
<input name="sport[3][]" type="checkbox" value="hocket">

<input name="sport[7][]" type="checkbox" value="baseball">
<input name="sport[7][]" type="checkbox" value="basquetball">
<input name="sport[7][]" type="checkbox" value="football">
<input name="sport[7][]" type="checkbox" value="hocket">

where 3 and 7 are the corresponding personId. So to do the insert:

foreach($_POST['sport'] as $personId=>$sports)
{
  foreach( $sports as $value)
  {
   $sql = sprintf("INSERT INTO `Atletes`(`personId`,`sportName`) VALUES('%s','%s')"
                ,mysql_real_escape_string( $personId)
                ,mysql_real_escape_string($value)
                );
  }
}

and will you please help me in displaying the value from the database too,

all you have to do is to execute a select statement:

$result=mysql_query("SELECT personId,sportName FROM Athletes") or die( mysql_error() );
while($row=mysql_fetch_assoc($result))
{
  echo sprintf(PHP_EOL.'<div><input type="textbox" name="sport[%s][]" value="%s"/></div>',  $row['personId'], $row['sportName'] );
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.