0

im doing something where users has a local database and when he clicks to checks new books, it get all the IDS(fixed) form his local database and create String separeted by comma (1,2,3,4,5) and then do a GET to my server

www.myserver.com/getNews?ids=1,2,4,10

and in the server side i do this:

1) Get the last ID(fixed) and set in a var called $total 2) get the IDS send by the user and create a array using .explode(",") 3) get the missing values $missing = array_diff(range(1,$total),$ids); get max id and get the missing numbers between the $total and $ids

and here come the part that i think its heavy:

for each $missing value i do a select and build a array to display as json

    foreach($missing as $m) {

         $sql = "SELECT * FROM `books` WHERE id='$m'";
while($row =mysqli_fetch_assoc($result))
    {


$emparray[] = array_map('utf8_encode', $row);
    }
}
    echo json_encode($emparray);

this is the only one approach or is there any other more light function?

2
  • 1
    This is commonly known as n + 1 query problem. Commented Nov 12, 2015 at 13:33
  • @MarcoAurélioDeleu going to read thank you man (Valeu ;)) Commented Nov 12, 2015 at 13:45

1 Answer 1

4

you can try this way. Implode your array with comma then use NOT IN condition in your query to select all books you want.

$strMissing = implode(',', $missing);

$sql = "SELECT * FROM `books` WHERE id NOT IN (".$strMissing.")";
Sign up to request clarification or add additional context in comments.

1 Comment

jesus thats just perfect!! You know the tool very nice, reduced 60lines to just almost 10. Worked perfectly! the only thing i had to change was the $missing to the $ids (var of ids that the user already has in his Database), $missing can be removed from my code thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.