Jack Cykor Jack Cykor - 1 year ago 55
HTML Question

Php logic whether to use if else conditionals or polymorphism

Guys what I m trying to implement here is I have suppose 5 buttons (with different options,which are displayed one after the another using jquery and data is sent using ajax).

<div id="div1">
<button value="1" class="div1button">1</button>
<button value="2" class="div1button">2</button>
<button value="3" class="div1button">3</button>
<button value="4" class="div1button">4</button>
<div id="div2">
<button value="a" class="div2button">a</button>
<button value="b" class="div2button">b</button>
<button value="c" class="div2button">c</button>
<button value="d" class="div2button">d</button>

Now the div 2 is hidden when the user clicks any one of the button on div1 ... div2 is displayed, the value of the button clicked is passed using jquery and sql query is executed using ajax..
Now the php which execute the query contains


The php checks where val1 is defined or not and the vice versa after val of div 2 is obtained ... the problem is here....

I have around 5 divs the now I need to check the values of all div exist or only 1 or 2 .. etc .... HOW to solve this?
To check this I have to implement to many if else
if div1 is defined ... do this
if div1 and div2 is defined ...do that
if div1 and div2 and div3 is defined ... do something
if div2 and div3 and div5 is defined

So this is where I'm stuck.

I'm a beginner please help, is there a better way to achieve what I want?


Thanks to @Igor

$selected = array('val1' => null, 'val2' => null, ...);
$selected['val1'] = $_GET['valDiv1'];
$selected['val2'] = $_GET['valDiv2'];
foreach($elements as $val => $key) {
if($val == 'val1' && $key == 'any') {
$sql = "SELECT * FROM details";
} else {
if($key != null) {
if($key != 'any') {
if($i>0) {
$sql .= " AND $val='$key'";
} else {
$sql = "SELECT * FROM details WHERE $val='$key'";

Answer Source

I am sure there are lots of approaches to optimize it. One of them could be to store all the choices not in separate variables, but in an array, e.g.:

$selected = array('val1' => null, 'val2' => null, ...);
$selected['val1'] = $_GET['valDiv1'];
$selected['val2'] = $_GET['valDiv2'];

And when checking you could do

if (array_search(null, $selected) === false) {