matching comma separated string to a database field and sort the result to be in the same order as the comma separated string

Issue

I have a variable with comma separated string, so I’m matching them with the values of another table field, how do I sort the result by the order in which the comma separated strings are structured. thank you currently I’m doing this.

$email_address = [email protected],[email protected],[email protected],; 
 
$sql ="SELECT id,company_ref,name FROM  employee WHERE email_address IN ('".str_replace(",", "','",    $email_address)."')";
 
$result = mysqli_query($db_conx, $sql);
$total = mysqli_num_rows($result);
   

Solution

You can use ORDER BY FIELD

ORDER BY field(email_address, '[email protected]','[email protected]','[email protected]');

Reference: https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_field

Answered By – Rikesh

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published