简体   繁体   中英

SQL select with multiple values and variable data

I have a table that contains a Job Number field (jobno). This field contains data that looks like '123456' or it could look like '345678 Acme'. Users of the website will type in a request for a job number. I have no problem searching and returning the desired data using a simple SELECT - WHERE - LIKE command. My problem is, users want to be able to now enter multiple Job numbers in their request field. ie: 123456, 345678. Etc.

How would I go about creating a select for this? I understand the use of the "WHERE jobno IN" and this method works fine for job numbers that are only a number. However, this does not allow for wildcards therefore I'm unable to return data such as '345678 Acme'. Also, I cannot use a series of "OR" because I would not know how many job numbers the user might enter to search for.

I hope this is enough explanation. Any help would be great. Thanks!

You should first do an explode of the input from the user. Then you have different options of what you could do, you could run a query for each number, and then just add all the resulting rows to an array (you could get duplicated results), or you could build the query on the fly.

Example:

// Input $_POST['jobNo'] = '123,1234,abc,abcde'
$str = $_POST['jobNo'];
$pieces = explode(',',$str); // returns array("123","1234","abc","abcd")
$sql = "SELECT * FROM table WHERE (";
$i = 0;
foreach( $pieces as $piece )
{
    if( $i !== 0 )
        $sql .= 'OR ';
    $sql .= "column LIKE '%". $piece ."%' ";
    $i++;
}
if( $i === 0 )
    $sql .= "1 = 1";

$sql .= ")";

// $sql = SELECT * FROM table WHERE (column LIKE '%123%' OR column LIKE '%1234%' OR column LIKE '%abc%' OR column LIKE '%abcd%') 

You could do:

$jobs = "1234, 4567, 89abc"; //input string of jobno's

$jobs = array_map(function($value) {
    return "jobno LIKE '%" . trim($value) . "%'";
}, explode(",", $jobs));
$condition = implode(" OR ", $jobs);

// condition will be:
// "jobno LIKE '%1234%' OR jobno LIKE '%4567%' OR jobno LIKE '%89abc%'

Option 1: Dynamic ORs in query:

$searchTerms = mysqli_real_escape_string($conn, $_POST['search']);
$where = [];
foreach (explode(",", $searchTerms) as $term) {
    $where[] = "job = '".trim($term)."'";
}
$query = "SELECT * FROM jobs WHERE ".implode(" OR ", $where);
// => SELECT * FROM jobs WHERE job = '123456' OR job = '345678 Acme'

Option 2: Regexp

$searchTerms = mysqli_real_escape_string($conn, $_POST['search']);
$where = array_map("trim", explode(",", $searchTerms));
$query = "SELECT * FROM jobs WHERE job REGEXP '^(".implode("|", $where).")$'";
// => SELECT * FROM jobs WHERE job REGEXP '^(123456|345678 Acme)$'

Adjust as needed for exact match or loose match

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM