Dale Franklin
Dale Franklin

Reputation: 1

How to use exploded data in new query?

I need to run a query on each part of the array coming out of explode.
Right now I just echo each word out from the explode, but I need to run a query like this for each word in the explode:

(select * from words where word = $split_phrase[$i])

I am wondering how to deal with the separate queries that need to run. Can I combine then in some way with the for loop?

I have check other posts, but nothing seems to address this directly.

Code Sample:I have 2 tables phrases words

<?

/*  Table: phrases   */

$ID = 'ID'
$TARGET = 'TLP'

/*  Table: words   */

$ID_Split = 'ID';
$Word_Split = 'Word';
$WBW_Split = 'WBW';

?>


<table width="800">
<tr>
<th>Display Word</th>
</tr>

<?
/* I pass in a variable from another page which is inserted into the query */

    $phrase_query = mysql_query("SELECT * FROM phrases WHERE id=" . $_GET['id']);



/* Loop through the search results and explode the string on the column variable $Target */


    while($rows=mysql_fetch_assoc($phrase_query)) {

        $split_phrase = explode(" ", $rows[$TARGET]);



/* Loop through the string and list each word from the explode array / 
the html table in the echos is started outside the PHP tags */

    for($i = 0; $i < count($split_phrase); $i++)        {

        echo "<tr>";
        echo "<td>" .$split_phrase[$i] . "</td>";
        echo "</tr>";
                                                        }

?>

</table>

Upvotes: 0

Views: 316

Answers (1)

Oroboros102
Oroboros102

Reputation: 2254

Explode words

$words = explode(" ", $rows[$TARGET]);

Escape and add quotes (php >= 5.3)

array_walk($words, function(&$word) {$word = '"' . mysql_real_escape_string($word) . '"';});

Run query with IN condition

mysql_query('SELECT * FROM words WHERE word IN ('. join(', ', $words) .')');

And you better use PDO or mysqli instead of mysql - it is deprecated.

Upvotes: 1

Related Questions