-3

My code is :

$text = '12-10-4-32-45-name-sara-x-y-86';
$array = explode('-',$text);
foreach($array as $value) {
    $sql = mysql_query("SELECT * FROM `table` WHERE `pid`='$value' ORDER BY `id` LIMIT 3");
    while($row = mysql_fetch_array($sql)) {
        echo $row['title'];
        echo '';
    }
    echo '';
}

This code work full but if in $text use 150 variable , server down !

How optimize this code for most variable ?!

Thx

9
  • 1
    Use an IN clause, perhaps? $sql = mysql_query("SELECT * FROM table WHERE pid IN ($in) .... (Do note that the above code is still vulnerable to SQL injection. Also, mysql_* functions are deprecated. You should switch to MySQLi/PDO and properly escape the input using prepared statements.) Commented May 7, 2014 at 13:32
  • Learn about MySQL IN clause Commented May 7, 2014 at 13:32
  • This question might help you: stackoverflow.com/questions/8270134/… Commented May 7, 2014 at 13:32
  • put all your values in 1 string variable, separated by ",", and put that in your query. Use in your query the pid IN (......) Commented May 7, 2014 at 13:33
  • Thx, But for each variable echo 3 title ! how fixed it ?! Commented May 7, 2014 at 13:35

1 Answer 1

0

If you need all of them as ids (which includes a string which is weird). Consider this example:

$text = '12-10-4-32-45-name-sara-x-y-86';
$text = array_unique(explode('-', $text)); // just in case there are duplicate ids
$statement = 'SELECT * FROM `table` WHERE `pid` IN("'.implode('", "', $text).'") ORDER BY `id` LIMIT 3';

// should be like this
// SELECT * FROM `table` WHERE `pid` IN("12", "10", "4", "32", "45", "name", "sara", "x", "y", "86") ORDER BY `id` LIMIT 3
// then just continue on your mysql_query
$sql = mysql_query($statement);
while($row = mysql_fetch_assoc($sql)) {
    // print your values or whatever it is you need to do
    // echo $row['title'];
}

Note: You don't need to query each value, that would be a total waste of resources. Imagine your text has (as you said) 150 numbers. Try to use the IN() of mysql so that it just make a single trip of query.

Sign up to request clarification or add additional context in comments.

4 Comments

Thx, But i use NUMBER AND VARCHAR !
@user3612383 if you really need them all to be inside the query, i edited the answer
Thx, But this code return last 3 three query. but i want get last 3 three query for each value of $text
Well this situation was not specified earlier, and the current answer does not meet that situation. if you really want to query each values of $text, then i can suggest using msqli multi_query instead, or you could, first each query assign it inside an array, then free the result

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.