View Full Version : The logic of a noob

04-20-2012, 05:18 AM
Hi guys, I am a beginner php coder, I have written some code below, basically it works - but it seems illogical to copy the code 21 times, I tried to write a function for it but the function doesnt like $_POST values as input, have a look and see if you can point me in the right direction of some learning material / concepts. I repeat, not after a way to fix the code - it works, just some reccomendations on how to program smarter!

if (isset($_POST['week']) and ($_POST['week']=="week_1")) {
if(isset($_POST['week_1_1'])) {
$item_1 = $_POST['week_1_1'];
if(isset($_POST['week_1_2'])) {
$item_2 = $_POST['week_1_2'];
if(isset($_POST['week_1_3'])) {
$item_3 = $_POST['week_1_3'];
if(isset($_POST['week_1_4'])) {
$item_4 = $_POST['week_1_4'];
if(isset($_POST['week_1_5'])) {
$item_5 = $_POST['week_1_5'];
if(isset($_POST['week_1_6'])) {
$item_6 = $_POST['week_1_6'];
if(isset($_POST['week_1_7'])) {
$item_7 = $_POST['week_1_7'];

This only the first 7, it continues for another 14 times! And to top it off I have to run it 6 times on the same page!

04-20-2012, 06:05 AM
You could use array for ordered data like that and avoid the repeating line of code of similar data

//built array for valid $_POST key
for ($i = 1; $i <= 21; $i++) {
$weeks[$i] = "week_1_$i";
//And then iterate it. The rest is up to you :D

04-20-2012, 08:13 AM
though I don’t see what the use/advantage of the (original) code would be. it literally does: "assign a given POST parameter to a certain variable if the former is set. if not, do nothing." that means that if $_POST['week_1_1'] is not set, using $item_1 would cause a warning (at least).

despite the fact that just renaming hides the attack potential of the input data.


$item = $_POST['item'];

// lots of code

// looks safe? and KABOOOM you fell into the SQL Injection trap
$sql = "SELECT a_field FROM my_table WHERE item = $item";

// this is not better, but you immediately SEE the problem
$sql = "SELECT a_field FROM my_table WHERE item = " . $_POST['item'];

04-20-2012, 12:23 PM
thanks for the feedback guys