Maydha Mn Maydha Mn - 6 months ago 23
MySQL Question

How to Display MySQL data as a checklist on HTML website?

It's not a very complex problem but I've been stuck for the past few days and can't seem to figure it out. I have a database called "major_degrees" and I want to fetch all the majors from the table called "majors" in this database and then display it as a checklist on my website using PHP and HTML.

I believe the fault is somewhere in my while loop.. it is printing the data as text but I want it as a checklist so I can check off the options I want and save them.

Here is the PHP code I have so far:

<?php

$username = "root";
$password = "";
$hostname = "localhost";

$dbname = "major_degrees";
$str='';

// Create connection
$conn = new mysqli($hostname, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT degree_name FROM majors";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row['degree_name'];
echo "<br/>";
}
return $str;
}
$conn->close();


?>

Answer

Try this:

<?php

    $username = "root";
    $password = "";
    $hostname = "localhost";

    $dbname = "major_degrees";
    $str='';

    // Create connection
    $conn = new mysqli($hostname, $username, $password, $dbname);

    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 

    $sql = "SELECT degree_name FROM majors";
    $result = $conn->query($sql);

    $out = '';
    $cnt = 0;
    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
            $cnt++;
            $out .= '<input id="cb_' .$cnt. '" class="someclass" type="checkbox" />' .$row['degree_name']. '<br/>';
        }
        echo $out;
    } 
    $conn->close();


?>

When ready to get the checked values and send them to another page:

jsFiddle Demo

$(document).ready(function(){

	$('#myForm').submit(function(evnt){
		evnt.preventDefault(); //suppress submitting form (for demo)
		var chk = $('#myForm').serialize();
		alert(chk);
	});

}); //END document.ready
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="myForm" action="submitTo.php" method="get">
	<input id="cb_1" name="cb_1" type="checkbox" /> Test 1<br>
	<input id="cb_2" name="cb_2" type="checkbox" /> Test 2<br>
	<input id="cb_3" name="cb_3" type="checkbox" /> Test 3<br>
	<input id="cb_4" name="cb_4" type="checkbox" /> Test 4<br>
	<input type="submit" value="Go" />
</form>

Comments