mysql - Writing a PDO search query from a PHP array -
i'm building application using php 7 , pdo connection mysql database.
one part of application contains search form allows user search training course 3 different fields: course category, course name, , date.
the types of elements on form are:
- course category - dropdown, numerical (int) id's.
- course name - text input
- date - date picker (using html 5
type="date"
parameter calendar in browser).
these fields can used in conjunction, or on own. means user search, example, (1), or (2 & 3), or (1 & 2 & 3).
i've written php post data , it's in array - example:
$search_data = [ 'category' => 3, 'name' => 'hazard training', 'date' => '' ]
i want use within pdo query don't know best way write because (1) , (3) =
query condition, whereas (2) like
. solution going looping through search terms , trying construct query, e.g.
$sql = ' '; foreach ($search_data $key => $value) { if ($key == 'category') { $sql .= ' category = ' . $value; } if ($key == 'course_name') { $sql .= ' course_name % ' . $value ' % '; } if ($key == 'date') { $sql .= ' date = ' . $value; } }
the trouble doesn't work because of having bind parameters in pdo. doesn't work because can't find way and
between each query (if there preceding statement).
i'm lost , unsure best way write is.
any appreciated.
edit: realise hardcoding names, e.g. ($key == 'course_name')
isn't ideal, being done because of different query conditions (like
vs =
). assume 1 make $search_data
multi-dimensional type of query was, beyond initial problem , post.
here`s simple solution problem:
$sql = 'select ..... ... 1 '; $where = ''; $pdodata = []; foreach ($search_data $key => $value) { if(!$value) continue; // skip empty values if ($key === 'category') { $pdodata[':category'] = $value; $where .= ' , category = :category '; } if ($key === 'course_name') { $pdodata[':course_name'] = '%'.$value.'%'; $where .= ' , course_name (:course_name) '; } if ($key === 'date') { $pdodata[':date'] = $value; $where .= ' , date = :date '; } } $sql = $sql.$where; $stmt = $this->ci->db->prepare($sql); $stmt->execute($pdodata); $results = $stmt->fetchall(pdo::fetch_assoc);
and have $pdodate
array holding binded data.
Comments
Post a Comment