Question

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

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top