How optimize while in while code? [duplicate]

荒凉一梦 提交于 2019-12-14 04:13:04

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/23519227/how-optimize-while-in-while-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!