Cosmi
Cosmi

Reputation: 67

PHP - strstr() doesn't work well with MySql

I have these tables in my DB:

TABLE A:

id | haystack
-------------
1  | 682,401
2  | 351

TABLE B:

id | needle
-------------
1  | 352
2  | 682
3  | 978

All I want to do is to check if a haystack from table A contain any needle from table B. I did this code in PHP:

$res_A = mysql_query('SELECT * FROM table_A');
while($row_A = mysql_fetch_array($res_A)){
    $res_B = mysql_query('SELECT * FROM table_B');
    while($row_B = mysql_fetch_array($res_A)){
        if(strlen(strstr($row_A['haystack'], $row_B['needle']) > 0)){
            echo 'I found this needle: '.$row_B['needle'].' in this haystack: '.$row_A['haystack'].'<br />';
        }
    }
}

But, it doesn't work. I tried to figure it out all day, but no chance. I need to mention that the haystack and needle columns are Varchars.

Can you help me with this situation? Thanks in advance!

Upvotes: 0

Views: 1105

Answers (3)

Rem.co
Rem.co

Reputation: 3821

Why don't you keep it all on the SQL server? Much easier and faster..

SELECT * from hay, needle WHERE hay.haystack LIKE CONCAT('%',needle.needle,'%');

Upvotes: 1

keithhatfield
keithhatfield

Reputation: 3273

Notice your Parenthesis placement on strlen(strstr($row_A['haystack'], $row_B['needle']) > 0)

Try: if(strlen(strstr($row_A['haystack'], $row_B['needle'])) > 0)

You are including the > 0 in the call to strlen

Upvotes: 1

Jeff Lambert
Jeff Lambert

Reputation: 24661

Try this:

$res_A = mysql_query('SELECT haystack FROM table_A');
while($row_A = mysql_fetch_array($res_A)){
    $res_B = mysql_query("SELECT needle FROM table_B WHERE needle = '" . $row_A['haystack'] . "'");
    if(mysql_num_rows($res_B) > 0) {  
            echo 'I found this needle: '.$row_B['needle'].' in this haystack: '.$row_A['haystack'].'<br />';
    }
}

Upvotes: 0

Related Questions