Can somebody tell me how to echo a checked checkbox with a table from database? Kindly help?

<?php
include "config.php";
?>
<!doctype html>
<html>
  <head>

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

    if(!empty($_POST['lang'])) {

      $lang = implode(",",$_POST['lang']);

      // Insert and Update record
      $checkEntries = mysqli_query($con,"SELECT * FROM languages");
      if(mysqli_num_rows($checkEntries) == 0){
        mysqli_query($con,"INSERT INTO languages(checkbox) VALUES('".$lang."')");
      }else{
        mysqli_query($con,"UPDATE languages SET checkbox='".$lang."' ");
      }
 
    }

  }
  ?>
  </head>
  <body>
  <form method="post" action="">
    <span>Select languages</span><br/>
    <?php

    $checked_arr = array();

  

    // Create checkboxes
    $languages_arr = array("Nearmisscase","FirstAidCase","LostTimeInjury","Fatal","Fire","Emission/Discharge/Spill/Leak(Abnormal)","Property Damage","HIPO");
    foreach($languages_arr as $checkbox){

      $checked = "";
      if(in_array($checkbox,$checked_arr)){
        $checked = "checked";
      }
      echo '<td><input type=checkbox name=lang[]  value="'.$checkbox.'" '.$checked.' > '.$checkbox.'</td>';
    }
    ?>
 
    <input type="submit" value="Submit" name="submit">
  </form>

  </body>
</html>

<?php


  // Fetch checked values
    $fetchLang = mysqli_query($con,"SELECT * FROM languages");
    if(mysqli_num_rows($fetchLang) > 0){
      $result = mysqli_fetch_assoc($fetchLang);
      $checked_arr = explode(",",$result['checkbox']);
    }

// Create checkboxes
    $languages_arr = array("Nearmisscase","FirstAidCase","LostTimeInjury","Fatal","Fire","Emission/Discharge/Spill/Leak(Abnormal)","Property Damage","HIPO");
    foreach($languages_arr as $checkbox){

      $checked = "";
      if(in_array($checkbox,$checked_arr)){
        $checked = "checked";
      }
      echo ' 
                                
                                   
                                    
                               
                                    
                                    <td><input disabled type=checkbox name=lang[]   value="'.$checkbox.'" '.$checked.' > '.$checkbox.'</td>
                                    
                                  ';
      
    }
    ?>                                               
              
                        


Now i want to display the checked checkbox inside this table?

<table>
                                <tr>
                                    <th>Nearmisscase</th>
                                    <th>First Aid Case</th>
                                    <th>Lost Time Injury</th>
                                    <th>Fatal</th>
                                    <th>Fire</th>
                                    <th>Emission/Discharge/Spill/Leak(Abnormal)</th>
                                    <th>Property Damage</th>
                                    <th>HIPO</th>
                                </tr>
                                <tr>
                                    <td><input type="checkbox" value="Nearmiss case" name="checkbox"></td>
                                    <td><input type="checkbox" value="First Aid Case" name="checkbox"></td>
                                    <td><input type="checkbox" value="Lost Time Injury" name="checkbox"></td>
                                    <td><input type="checkbox" value="Fatal" name="checkbox"></td>
                                    <td><input type="checkbox" value="Fire" name="checkbox"></td>
                                    <td><input type="checkbox" value="Emission/Discharge/Spill/Leak(Abnormal)" name="checkbox"></td>
                                    <td><input type="checkbox" value="Property Damage" name="checkbox"></td>
                                    <td><input type="checkbox" value="HIPO" name="checkbox"></td>
                                </tr>
                            </table>
<style>
                                table {
                                    font-family: sans-serif;
                                    border-collapse: collapse;
                                    width: 75.5%;
                                    font-size: 15px;
                                }

                                td,
                                th {
                                    border: 1px solid black;
                                    text-align: center;
                                    padding: 2px;
                                    font-weight: normal;
                                }

                            </style>

Okay, well I can tell you the database squad will be along momentarily to tell you that’s not a good way to store your data. I will for the moment proceed with your current layout.

You’ve already got the correct code for the echo in your PHP, but something’s missing:

    <?php

    $checked_arr = array(); //This is where your problem is.


    // Create checkboxes
    $languages_arr = array("Nearmisscase","FirstAidCase","LostTimeInjury","Fatal","Fire","Emission/Discharge/Spill/Leak(Abnormal)","Property Damage","HIPO");
    foreach($languages_arr as $checkbox){

      $checked = "";
      if(in_array($checkbox,$checked_arr)){ //This will never be true; $checked_arr is empty!
        $checked = "checked";
      }
      echo '<td><input type=checkbox name=lang[]  value="'.$checkbox.'" '.$checked.' > '.$checkbox.'</td>';
    }
    ?>

Yes, absolutely correct - storing multiple values in a single column just makes it difficult to use the data. You should have these options in separate rows, linked via a common unique id. It’s difficult to see from the sample code how these values are used elsewhere, but it’s difficult to think of a scenario to justify the concatenated strings.

While you’re looking at database normalisation, you should also look at prepared statements, for a whole host of reasons better than concatenating strings into queries.

I agree with the comments already posted and in general a comma separated string can be a pain to deal with, but taking into consideration that you are checking for number of rows to process an insert or update query and not passing any other DB fields (record_id) that would indicate this would be used in multiple cases, a single db record does make it easy. If you are going to be dealing with multiple cases then looking into DB normalization is recommended and the page and processing code changed to only update specific cases.

All this being said, the opening question was simply regarding making checkboxes checked based on the DB record and you were heading in the right direction. I updated your sample using prepared statements and all queries and processing above output to browser in a more logical order.

<?php
include "config.php"; 

	if(isset($_POST['submit'])){
	
		if(!empty($_POST['lang'])) {
		
			$lang = implode(",",$_POST['lang']);
			
			// Insert and Update record
			$checkEntries = mysqli_query($con,"SELECT * FROM languages");
			
			if(mysqli_num_rows($checkEntries) == 0){					  
				$sql_save_languages = "INSERT INTO languages(checkbox) VALUES(?)";
			}else{		
				$sql_save_languages = "UPDATE languages SET checkbox = ?";
			}
			
			$query_save_languages = $con->prepare($sql_save_languages);
			$query_save_languages->bind_param("s", $lang); 		
			$query_save_languages->execute();	
		}
	
	}

// Create checkboxes
$languages_arr = array(
	 "Nearmisscase"=>"Near Miss Case"
	,"FirstAidCase"=>"First Aid Case"
	,"LostTimeInjury"=>"Lost Time Injury"
	,"Fatal"=>"Fatal"
	,"Fire"=>"Fire"
	,"Emission/Discharge/Spill/Leak(Abnormal)"=>"Emission/Discharge/Spill/Leak(Abnormal)"
	,"Property Damage"=>"Property Damage"
	,"HIPO"=>"HIPO"
);
   
$checked_arr = array();

// Fetch checked values
$fetchLang = mysqli_query($con,"SELECT * FROM languages");
if(mysqli_num_rows($fetchLang) > 0){
	$result = mysqli_fetch_assoc($fetchLang);
	$checked_arr = explode(",",$result['checkbox']);
}
  
?>
<!doctype html>
<html>
	<head>
		<style type="text/css">
		table {
			font-family: sans-serif;
			border-collapse: collapse;
			width: 75.5%;
			font-size: 15px;
		}
		
		td,
		th {
			border: 1px solid black;
			text-align: center;
			padding: 2px;
			font-weight: normal;
		}
		
		</style>
	</head>
	<body>
		<form method="post" action="">
			<span>Select languages</span><br/>
			<?php
				echo '<table>
					<tr>'."\r"; 
					foreach($languages_arr as $checkbox => $field):
						echo '<th>'.$field.'</th>'."\r";
					endforeach;
					echo '</tr>
					<tr>'."\r";
					// Create checkboxes
					foreach($languages_arr as $checkbox => $field):
					
					$checked = (in_array($checkbox,$checked_arr) ? ' checked="checked"' : '');
						echo '<td><input type=checkbox name=lang[]  value="'.$checkbox.'"'.$checked.'></td>'."\r";
					endforeach;
					
					echo '</tr>
				</table>'."\r";
			?>
			
			<input type="submit" value="Submit" name="submit">
		</form>
	
	</body>
</html>

Thanks a lot for the help and much appreciated. :slight_smile:

Thanks a lot for the help much appreciated. :slight_smile:

Thanks a lot for your kind help i was trying different ways. It is working great. Again thanks a lot. :slight_smile:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.