Jump to content

SQL statement generation via array


PolarisX

Recommended Posts

The subject of this topic may not be an excellent explanation of what I'm trying to achieve but its as close as possible. I'm trying to create an SQL statement based upon the selections of a submitted form. Essentially a random number of check boxes are selected in the form and based on those selections an SQL statement is generated. The html of the form to give a little insight into that end consits of this:

 

<label for="Item1">Item1</label>    <input type="checkbox" name="item[]" value="Item1" id="Item1" /><br />
<label for="Item2">Item2</label>    <input type="checkbox" name="item[]" value="Item2" id="Item2" /><br />
<label for="Item3">Item3</label>    <input type="checkbox" name="item[]" value="Item3" id="Item3" /><br />

 

I have never done this kind of thing before and I've coded myself into a corner now and i cant think my way out. I tried to simplify my code; thinking I could wrap my mind around it and this is what that got me:

 

$sql = "SELECT * FROM `table` WHERE ";
$items = count ( $_REQUEST ['item'] );
$cnt = 0;

if ($items == 0) {
die ( 'No topics selected' );
} elseif ($items == 1) {
$sql .= "`item` = '" . $_REQUEST ['item'] [0] . "' ";
} else {
do {
	if ($cnt <= ($items - 1)) {
		$sql .= "`item` = '" . $_REQUEST ['item'] [$cnt] . "' AND";
		$cnt ++;
	} elseif ($cnt == $items) {
		$sql .= "`item` = '" . $_REQUEST ['item'] [$cnt] . "' ";
		break;
	}
} while ( 0 );
}

$sql .= " LIMIT 0,8";

$itemList = $db->doQuery($sql);

 

This is in its simplest form, I would not use this in production, but this is essentially what im trying to do. I'm just having trouble turning this into a high performance piece of code that actually works, and I have the biggest case of coders block imaginable. Any help or suggestions would be most graciously appreciated.

Link to comment
https://forums.phpfreaks.com/topic/174157-sql-statement-generation-via-array/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.