我的代码是:
$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 '';
}
此代码完整但如果在$ text中使用150变量,服务器关闭!
如何针对大多数变量优化此代码?!
THX
答案 0 :(得分:0)
如果你需要所有这些作为id(包括一个很奇怪的字符串)。考虑这个例子:
$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'];
}
注意:您不需要查询每个值,这将浪费资源。想象一下你的文字(正如你所说)有150个数字。尝试使用mysql的
IN()
,以便只进行一次查询。