Note that there are some explanatory texts on larger screens.

plurals
  1. POSql Queries in a foreach slows down the page
    primarykey
    data
    text
    <p>I have a problem where I get an array of words and I have to insert every one of them in DB via a foreach, but the whole thing is running too slow.</p> <pre><code>foreach($words as $word) { // even more checks if(strlen($word) &lt; 3) continue; $word = $this-&gt;db-&gt;escapeString(strtolower($word)); // word not found? $result = $this-&gt;db-&gt;querySingle("SELECT id FROM words WHERE word = '{$word}'"); if(!$result) { $this-&gt;db-&gt;exec("INSERT INTO words (word) VALUES ('{$word}')"); $this-&gt;db-&gt;exec("INSERT INTO search (reply, word) VALUES ('{$id}', '{$this-&gt;db-&gt;lastInsertRowID()}')"); // word found } else $this-&gt;db-&gt;exec("INSERT INTO search (reply, word) VALUES ('{$id}', '{$result}')"); } </code></pre> <p>Basically lets say $words = array('hello', 'kitten'); Within that foreach, it will take my first word (hello) and check if it exists in the words table. If it cannot find the word, it will then insert it there and also insert it into another table with a variable $id that will not change within the foreach. If however it found the word it will insert it directly in the 2nd table. After that it will take the 2nd word (kitten) and do the same thing.</p> <p>Using php5 with sqlite3</p> <pre><code>$this-&gt;db = new \SQLite3(ROOT . DS . 'db' . DS . 'app.db'); </code></pre> <p>The tables in question are very light</p> <pre><code>CREATE TABLE words (id INTEGER PRIMARY KEY AUTOINCREMENT, word TEXT); CREATE TABLE search (reply INTEGER, word INTEGER); CREATE INDEX search_reply_idx ON search (reply); CREATE INDEX search_word_idx ON search (word); </code></pre> <p>This works fine most of the time for 10-15 words, but if i have over 150 words it will be as slow as 8 seconds. Can i combine the queries into just one? Am i missing something?</p> <p>Thanks.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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