优化foreach中的while和SQL

2021-12-26 00:00:00 process while-loop foreach php mysql

我的代码:

$text = '12-name-y-86';
$array = explode('-',$text);
foreach($array as $value) {
    $sql = mysql_query("SELECT * FROM `table` WHERE `pid`='$value' ORDER BY `id` LIMIT 3");
    echo '***'.$value.'***';
    echo '<br />';    
    while($row = mysql_fetch_array($sql)) {
        echo $row['title'];
        echo '<br />';
    }
    echo '<br /><br />';
}

打印:

12

标题1

标题2

标题3

姓名

ti1

ti2

ti3

t1

t2

tle3

86

mytitle1

mytitle2

mytitle3

此代码可以完全购买 $text 中的更多值,服务器已关闭!

This code work full buy for more values in $text , server has down !

推荐答案

尝试在一个查询中选择所有记录,如下所示:

Try to select all records in just one query, like this:

$text = '12-name-y-86';
$array = explode('-', $text);
$array = "'" . implode(',', $array) . "'";
$sql = mysql_query("SELECT * FROM `table` WHERE `pid` IN (' . $array . ') ORDER BY `id` LIMIT 3");
while($row = mysql_fetch_array($sql)) {
    echo $row['title'];
    echo '<br />';
}
echo '<br /><br />';

相关文章