Display checkboxes from mysql table rows

I* have a mysql table with only 1 field, set up like

CREATE TABLE amenities (
id SMALLINT AUTO_INCREMENT,
name VARCHAR(25),
PRIMARY KEY(id)
);

And added a few records to…

INSERT INTO amenities (name) VALUES (‘Washer/Dryer’);
INSERT INTO amenities (name) VALUES (‘Pet Friendly’);
INSERT INTO amenities (name) VALUES (‘Ocean View’);
INSERT INTO amenities (name) VALUES (‘Balcony’);
INSERT INTO amenities (name) VALUES (‘Bay View’);
INSERT INTO amenities (name) VALUES (‘Maid Service’);
INSERT INTO amenities (name) VALUES (‘TV’);
INSERT INTO amenities (name) VALUES (‘Internet/WiFi’);
INSERT INTO amenities (name) VALUES (‘Open Bar’);
INSERT INTO amenities (name) VALUES (‘Remodeled/New furnishings’);

I wanted to create a checkbox (yes/no) for each and was thinking this was the way

<?php 
    include('connect.php');
    $query = 'SELECT * FROM amenities'; 

    $r = mysql_query($query);

    while ($row = mysql_fetch_array($r)) { 
            echo "<input type='checkbox' name='".$row['name']."   value='".$row['GradeID']."' />"; 
        }
 
?>

is that right?

does it work for you?

I can’t see how that would work, given the difference between the id column name when you define the table, and the GradeID column name you use in the code.

Also, if it’s new code, dump the old no-longer-supported mysql calls and look at PDO or mysqli - one less part to change when you have to.

ok, got it
http://svr.teamluke.net/add_rental.php
I used the PDO method

  <?php 
include('db/configPDO.php');
$stmt = $dbh->query('SELECT name FROM amenities');
while ($row = $stmt->fetch())
{
	echo '<div class="checkbox">';
	echo '<label>';
	echo "<input type='checkbox' name='".$row['name']." value='".$row['name']."' />";
        echo '<span class="cr"><i class="cr-icon glyphicon glyphicon-ok"></i></span>';
	echo $row['name'];
	echo '</label>';
	echo '</div>';
}
?>

That’ll work, but in my opinion you should use the id field as the checkbox value, rather than the name. The name is a text field, could use all sorts of characters that might cause issues, isn’t marked as a unique field so there could be more than one the same. The auto-increment id won’t have any of those issues. My comment above about the id was just that you’d used the wrong name.

Is it correct that you open and close a new div for each checkbox, or do you mean them to all appear in the same one?

1 Like

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