A
A
Abc Edc2014-10-10 19:22:00
PHP
Abc Edc, 2014-10-10 19:22:00

How stupid is the logic?

I can not think over the logic when sampling (search). The person enters the parameters, but I want them all to be optional. I did this:

$name_user =$_POST['name_user'];
$surname_user =$_POST['surname_user'];
$city_user =$_POST['city_user'];
$resultArray = "SELECT * FROM `user` WHERE `name` ='$name_user' AND`surname`='$surname_user' AND `city` = '$city_user' ";
 
if ($name_user==""){
$resultArray = str_replace("`name` ='$name_user' AND","",$resultArray);
  }
  if ($surname_user==""){
$resultArray = str_replace("`surname`='$surname_user' AND","",$resultArray);
  }
  if ($city_user==""){
$resultArray = str_replace("`city` = '$city_user'","",$resultArray);
  }

BUT if there are options when a person, for example, entered only the Name and then the data does not come out anymore since AND is not cut out, how can it be more reasonable to do this without looking at each particular case?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
pws, 2014-10-16
@pws

The logic is fundamentally wrong.
This sample should be built based on what fields are entered, and not vice versa, remove the "extra"
As an example

$condition = array();
if ($username != "") {
$condition[] = " `username` = ' ". $username ."'";
}
if ($surname != "") {
$condition[] = " `surname` = ' ". $surname ."'";
}

And so on. You can generally make it in the form of a list of fields, so as not to copy-paste ...
And then we form the request itself
$SQL = "SELECT * FROM `users`";
if (count($condition) > 0) {
  $SQL .= " WHERE ".implode(" AND ", $condition);
}

I
iliyaisd, 2014-10-21
@iliyaisd

$condition = ""; 
foreach($_POST as $field => $value) { 
  $condition .= (!empty($_POST[$k]) ? " AND " . substr($field, 0, strlen($field)-5)" like '%" . $value . "%'" : ""); 
}
$query = "SELECT * FROM `user` WHERE " . substr($condition, 5);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question