本文介绍了优化while和SQL的foreach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的代码:
$ 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 />';
$ / code $ / pre
$ b $ p
标题3
名称
ti1
y
tle1
tle2
tle3
86
mytitle1
mytitle2
mytitle3 p>
这段代码在$ text中有更多的值,服务器已经关闭了!
解决方案 $ 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 />';
My code :
$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 />';
}
Print :
12
title1
title2
title3
name
ti1
ti2
ti3
y
tle1
tle2
tle3
86
mytitle1
mytitle2
mytitle3
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 />';
这篇关于优化while和SQL的foreach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!