Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>How about turning it on its head a little..</p> <p>Why not <strong>farm more out to the SQL statement itself</strong>? The initial loop to construct the statement will likely have to run fewer times than looping through each returned row if you simply execute an open ended statement, so will thus be faster..</p> <pre><code> $content = " stack overflow internet services, user contributions licensed under cc-wiki with attribution required and internet is a good service " ; $words = explode(" ", trim($content) ); //break the sentence to words with space $sql="SELECT `tag` FROM table_tags WHERE "; for ($i=0;$i&lt;sizeof($words); $i++){ $sql. = " `tag` ='". mysql_real_escape_string($words[$i])."'"; if($i!=sizeof($words)-1){ $sql.=" OR "; } } $result = $db-&gt;sql_query($sql); // returned rows will now ONLY be matching tags while ($row= $db-&gt;sql_fetchrow($result)) { $tag_title = $row[tag]; } print_r($tag_title); </code></pre> <p>So, if you had a recordset of 1000 rows (tags in your DB), and only 4 potential tags (words in your title), if you loop through the rows in PHP using the proposals above- the loop has to run 1000 times to simply identify 4 possible matches...if you move the criteria/identification to the SQL, the loop only has to run 4 times in order to build the initial filter, which is <strong>far more efficient</strong>. What it will also do is automatically prevent against duplicats - though if they exist in your DB, simply append <code>'GROUP BY tag'</code> to <code>$sql</code>..</p> <p>nb. As per the comment below- IN can be used instead of OR:</p> <pre><code> $sql="SELECT `tag` FROM table_tags WHERE `tag` IN ("; for ($i=0;$i&lt;sizeof($words); $i++){ $sql. = "'". mysql_real_escape_string($words[$i])."'"; if($i!=sizeof($words)-1){ $sql.=", "; } } $result = $db-&gt;sql_query($sql.")"); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload