A
A
Ayk722015-11-11 00:27:17
PHP
Ayk72, 2015-11-11 00:27:17

How to process data?

Goodnight!
I can't figure out how to process the data.
The bottom line is that there are n-th number of pairs of fields in the form:

<input type="text" name="text[god][1]" value="">
<input type="text" name="text[god][2]" value="">

Where:
god - field name
1, 2 - field values
​​There can be a lot of such pairs, and all of them have unique names, i.e. god.
The task is to process them and display them in the where sql query.
I did it differently, but always if the field [1] does not have a pair, then it takes the value [2] from the field of another field name god:
foreach ($_POST["text"] as $key3 => $value3) {
foreach ($value3 as $key4 => $value4) {
if($value4 != '') { 
if($key4 == 1) $wheres1 = $key3.' >= '.$value4;
if($key4 == 2) $wheres2 = $key3.' <= '.$value4;
}
}

if ($wheres1!='' && $wheres2!='') {
$wheres = '('.$wheres1.' AND '.$wheres2.')';
}else{
if($wheres1!='') $wheres = $wheres1;
if($wheres2!='') $wheres = $wheres2;
}
}

Can you tell me how to handle it well? So that if the field [1] does not have a pair, it does not take a value from another field. And insert it all into the sql query where.
Thanks in advance!!!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
wol_fi, 2015-11-11
@wol_fi

To begin with, I would recommend that you familiarize yourself with prepared statements - php.net/manual/ru/pdo.prepared-statements.php
And then, use some kind of query builder, like framework.zend.com/manual/current/en/modules/ zend....
and use it like this:

if ($condition) {
   $query->where('blabla = ?', $blabla)
} else {
   $query->where('foo = ?', $foo);
}

S
Stalker_RED, 2015-11-11
@Stalker_RED

Let's say I collected your request

$test_data['text']['god'][1] = 1234;
$test_data['text']['god'][2] = 5678;
$test_data['text']['cat'][1] = 111;
$test_data['text']['cat'][2] = 222;
$test_data['text']['meow'][2] = 888; // there is only one "meow"

$conditions = [];
foreach ($test_data['text'] as $fieldname => $values) {
  $subconditions = [];
  if (!empty($values[1])) $subconditions[] = $fieldname." >= ".intval($values[1]);
  if (!empty($values[2])) $subconditions[] = $fieldname." <= ".intval($values[2]);
  if(!empty($subconditions)) $conditions[] = '('.implode(' AND ', $subconditions).")\n";
}
$sql = "SELECT * FROM tbl_name\n";
if (!empty($conditions)) $sql .= 'WHERE '.implode(' AND ', $conditions);
echo '<pre>' . $sql;
/*
SELECT * FROM tbl_name
WHERE (god >= 1234 AND god <= 5678)
 AND (cat >= 111 AND cat <= 222)
 AND (meow <= 888)
*/

Demo: codepad.viper-7.com/ukJK5V
But this will only work if you train somewhere on your local server. And in general it is IMPOSSIBLE TO DO SO because sql injections are possible.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question