Link to home
Start Free TrialLog in
Avatar of Solenthaler
Solenthaler

asked on

mySQLI SELECT LIKE masked compare

Must search in a mysqli DB with 'SELECT * FROM table WHERE String like $string. A '?' in the reference String can represent any character but all the others in the $string must match.
Eg. the reference String ='abcd?efg' would match $stringa = 'abcdXefg' or $stringc = 'abcd1efg'. How does the mySQL "Select..." look like? Is ther a easy way.

$string = 'abcd?efg';    
$row = $mysqli->query("SELECT * FROM $table WHERE String LIKE '$string'");
$result = $row->fetch_assoc();
print_r( json_encode($result) );

Open in new window

Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

In MySQL there is a placeholder wild-card that is the percent sign, but I've never seen it embedded.  My first step would be to define what would match and what would not match, and set up a couple of test rows in a separate test table so I could do proof of concept.

Here is what I might do: $sql = "SELECT FROM myTable WHERE myColumn LIKE 'abcd%'";

When you run this query you will get a results set with all of the columns that match 'abcd' follwed by anything.  Then you can use an iterator to walk over the results set and discard the values you do not want.

There might be some kind of regular expression that you could use in the SQL statement, too.  Worth looking that up to see if you can match the pattern easily with REGEX.
https://dev.mysql.com/doc/refman/5.7/en/regexp.html
ASKER CERTIFIED SOLUTION
Avatar of chaau
chaau
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Yes, @chaau, the underscore notation definitely looks easier!  Good call!
Avatar of Solenthaler
Solenthaler

ASKER

Dear experts, did it  with an underscore like chaau proposed. The code above is not doing what i wanted.
Have you ever tried?
What is not working? How is your table called? Do you really have a column called string?
Hi all
$string = 'abcd?efg';  
$string = strtr($string, "?", "_");  
$row = $mysqli->query("SELECT * FROM $table WHERE  '$string' LIKE String ");
$result = $row->fetch_assoc();
print_r( json_encode($result) );

Open in new window

After i swaped the position String and $string the code is working.
Thanks to all