Search code examples
phpmysqldistinctsql-like

MySQL with a LIKE returning wrong row


I have the following:

 $q = "w0";

 $stmt = $db_found->prepare("SELECT DISTINCT callsign FROM NetLog WHERE callsign LIKE ?");
 $stmt->execute(array("%q%"));
 $result = $stmt->fetchAll();
 $print_r($result);

It returns:

Array
(
    [0] => Array
        (
            [callsign] => KA0QIG
            [0] => KA0QIG
        )

)

So what went wrong? Why am I only getting one return when the DB has many values for callsign with 'w0'?


Solution

  • You are using select distinct with no wildcards. So, you can only get at most one value.

    Perhaps you mean something like this:

    $q = "%w0%";
    
    $stmt = $db_found->prepare("SELECT DISTINCT callsign FROM NetLog WHERE callsign LIKE ?");
    $stmt->execute($q);
    $result = $stmt->fetchAll();
    $print_r($result);
    

    Your version was just looking for the letter "q".

    It occurs to me that you wanted:

    $stmt->execute(array("%$q%"));