Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

I'm trying to select all the rows from my database, where 'street' is LIKE the contents from an array ($streets).

Here's what I have...

    #TEXT AREA INPUT  = $streets
    $sql = "SELECT * FROM `data` WHERE `street` LIKE '%".implode("%' OR `street` LIKE     '%",$streets)."%'";
    echo $sql;
    $result = mysqli_query($con,$sql)  or die(mysql_error());
    $totalitems1 =  mysqli_num_rows($result);
    echo $totalitems1 . "<br>";
    while($row = mysqli_fetch_array($result))
    {
    echo $row['street']. "<br>";

    }

the varible $streets is exploded from a text area input, each value on a new line.

When I process this using PHP, only the rows that are LIKE the last 'OR' are returned .. (The last line in the text area). But when I copy and paste the generated SQL into PHPMYADMIN, it returns ALL the data, as expected.

What am I missing here? Thanks.

share|improve this question
1  
Try mysqli_fetch_assoc() instead of mysqli_fetch_array() – Fred -ii- Feb 19 '14 at 23:32
1  
Sidenote: You're also mixing mysqli_query with an mysql_* function mysql_error which will result in not showing the actual error message. – Fred -ii- Feb 19 '14 at 23:46
1  
Well spotted... – user3330410 Feb 19 '14 at 23:47
up vote 0 down vote accepted

My guess would be that you aren't stripping the newline from the end of each $street entry, therefore only the last entry looks valid as it probably doesn't have a trailing newline. No doubt your query probably looks like...

SELECT * FROM `data` WHERE `street` LIKE '%foo
%' OR `street` LIKE '%bar
%' OR `street` LIKE '%baz%'

The quick fix would be to use...

implode("%' OR `street` LIKE '%", array_map(function($s) use ($con) {
    return $con->escape_string(trim($s));
}, $streets))

Ideally, you should be using a prepared statement with parameter binding.

share|improve this answer
    
SUPER! Thank you very much. I guess when you've been going all day, you look over the simple things. Thanks again Phil. – user3330410 Feb 19 '14 at 23:52

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.