Creating a dynamic search query with PHP and MySQL

I am trying to create a dynamic search query based on user input.

Requirements:

  • The user can fill in any, several or all fields.
  • The query searches the table for the record that meets all the requirements.

Now I have done my research, and I have found several ways to do this. But none of them work, and if they do, they are far from practical.

Attempt:

I am currently creating a query like this:

SELECT * 
FROM assignments 
WHERE (id = $id OR id = '') 
  AND (field1 = $field1 OR field1 = '')

This query works, but only if you fill in all the fields.

I got this from the stackoverflow article, which I can no longer find by saying:

, "id = $input"      - , "id =" "      , . .

, , .

?

+4
3

- , , ,

<?php
$id = $_POST[id];
$field1 = $_POST[field1];
$field2 = $_POST[field2];
$field3 = $_POST[field3];

$whereArr = array();
if($id != "") $whereArr[] = "id = {$id}";
if($field1 != "") $whereArr[] = "field1 = {$field1}";
if($field2 != "") $whereArr[] = "field2 = {$field2}";
if($field3 != "") $whereArr[] = "field3 = {$field3}";

$whereStr = implode(" AND ", $whereArr);

$query = "Select * from assignments WHERE {$whereStr}";

- ,

+9

, , WHERE, , , , PHP "implode", AND "".

startquery voila!

, atm!

+2

. , , - REGEXP MySQL. , , "maverick" Top Gun, REGEXP = 'mav' | "" . , .

REGEXP, .

0

All Articles