Home Ask Login Register

Developers Planet

Your answer is one click away!

f7n February 2016

How to build an SQL query from HTML checkboxes?

I need to create a query builder for SQL, where you can choose query constraints via HTML checkboxes. Each checkbox has a name,used for a column name (e.g ActorName), and a value for the column value (like Tom Hanks).

I'm having trouble deciding what is the best way to do this. I've tried adding/removing to a JavaScript object, and then iterating through each key-value pair, i.e each ActorName, each DirectorName, and append them to the WHERE constraint in SQL, but as the checkbox names are not unique, i.e there are many Actors, Genres etc, it complicates things. Right now, I'm using this method:


On checkbox checked, add the checkbox's name and value to a JS object, with the ActorName as the object key (as this will always be unique), and the checkbox name as the object value. I have a feeling this is bad practice, and I'm sure there is a better way to achieve my goal, but I'm out of ideas.

can anyone recommend a better method of building a query from checkboxes?


Xenofexs February 2016

You can use "serialize" for get and send data with Ajax

First, add a form balsise in your HTML code

Example :

    <div id="checkboxes">
            <input type="checkbox" value="Tom Hanks" name="actorName[]">Tom Hanks</label>
            <input type="checkbox" value="Tim Allen" name="actorName[]">Tim Allen</label>
            <input type="checkbox" value="Don Rickles" name="actorName[]">Don Rickles</label>
            <input type="checkbox" value="Jim Varney" name="actorName[]">Jim Varney</label>
            <input type="checkbox" value="Wallace Shawn" name="actorName[]">Wallace Shawn</label>
            <input type="checkbox" value="Fantasy" name="genreName[]">Fantasy</label>
            <input type="checkbox" value="Comedy" name="genreName[]">Comedy</label>
            <input type="checkbox" value="Children" name="genreName[]">Children</label>
            <input type="checkbox" value="Animation" name="genreName[]">Animation</label>
            <input type="checkbox" value="Adventure" name="genreName[]">Adventure</label>
            <input type="checkbox" value="USA" name="countryName">USA</label>

Your javascript :

    $(':checkbox').change(function() {

function sendData () {
    var $form = $('form');
            url : 'ajax.php',
            data: $form.serialize(),
            async : false,
            success : function(response){

Post Status

Asked in February 2016
Viewed 1,402 times
Voted 6
Answered 1 times


Leave an answer

Quote of the day: live life