John DOe
John DOe

Reputation: 222

How do I use a regex in my MySQL query?

I want to search for a word+number if that SQL returns nothing, I will default it to a full LIKE search, is there any way to implement regex like this in SQL?

Example:

$queryWord = potato

Like this:

$sql = "SELECT * FROM `words` WHERE `searchWord` LIKE '$queryWord+number';";
$result = mysqli_query($con, $sql);

if (mysqli_num_rows($result) == 0) {

    $sql =  "SELECT * FROM `words` WHERE `searchWord` LIKE '%$queryWord%';"; // full search
    $result = mysqli_query($con, $sql);
    // etc etc

}

Upvotes: 2

Views: 97

Answers (1)

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

Just change your query to this:

$sql = "SELECT * FROM `words` WHERE `searchWord` REGEXP '$queryWord(\d{1,4})';";

and here is a Rubular that proves the Regex.

Upvotes: 3

Related Questions