简体   繁体   中英

checkbox check with database data

i have two mysql tables and looks like as follows. iam using PHP and MySQL

CREATE TABLE IF NOT EXISTS `subject_category` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`sid` int(5) DEFAULT NULL,
`category` varchar(50) DEFAULT NULL,
`subject` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=191 ;

INSERT INTO `subject_category` (`id`, `sid`, `category`, `subject`) VALUES
(1, 1, 'GCE O/L', 'Sinhala'),
(2, 2, 'GCE O/L', 'Development Studies'),
(3, 3, 'GCE O/L', 'History'),
(4, 4, 'GCE O/L', 'Mathematics'),
(5, 5, 'GCE O/L', 'Citizan Education'),

and

CREATE TABLE IF NOT EXISTS `user_subjects` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`uid` bigint(20) NOT NULL,
`usid` int(4) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=43 ;

INSERT INTO `user_subjects` (`id`, `uid`, `usid`) VALUES
(11, 142247454430186, 1),
(12, 142247454430186, 3),
(13, 142247454430186, 5)

actually what i need is, need to create check-box array using first table data. this part is already done. then i need to checked checkbox match with second table (subject_category.id=user_subjects.usid) for the particular user_subject.uid

FINALLY i need 5 check boxes for data in first table and 3 of them have selected with to second table values

please help me to solve this problem

I think you start off the wrong way, you should do it in 1 step, not in two steps.

The mysql query you need is:

$query = 'SELECT sc.subject, CASE WHEN us.id IS NULL THEN "" ELSE "checked" AS checked
 FROM subject_category sc
  LEFT JOIN user_subjects us ON (us.usid = sc.id)';

With the result of this query you should be able to generate the checked and unchecked checkboxes at once.

NOTE: I don't know which columns you need and if you needed sc.id or sc.sid in the join, but I think you can create the right query with this example.

Next step PHP (with mysql_* function as the TS asks in comment, I know you should use PDO or mysqli):

$result = mysql_query($query);
while ($line = mysql_fetch_assoc($result)){
  echo '<input type="checkbox" checked="'.$line['checked'].'" name="subject" value="'. $line['subject'] .'" /> '.$line['subject'];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM