Search code examples
mysqlsqlwildcardsql-like

PHP SQL PDO Wildcard query


I have a table with these values:

123, 159, 147, 258, 369

I need to find the data that both includes 1 and 2 but not 3. The result should be:

159, 147, 258

I have tried the Wildcard operators % - [] and no luck.

$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);

$sql = "SELECT * FROM numbers WHERE track LIKE '%[12]%' AND track NOT LIKE '%[3]%'";
$q = $conn->prepare($sql);
$q->execute(array($title));

Solution

  • The syntax you're using works in SQL Server but not MySQL. You could use REGEXP:

    WHERE track REGEXP '[12]'
    AND track NOT LIKE '%3%'
    

    Or just use LIKE:

    WHERE (track LIKE '%1%' OR track LIKE '%2%')
    AND track NOT LIKE '%3%'