将MySQL查询放入PHP循环是否不好? [英] Is it bad to put a MySQL query in a PHP loop?
问题描述
我经常需要运行MySQL查询来处理大型数组或PHP中的大量动态数据.
I often have large arrays, or large amounts of dynamic data in PHP that I need to run MySQL queries to handle.
是否有更好的方法来运行诸如INSERT或UPDATE之类的许多进程而无需遍历要进行INSERT或UPDATE的信息?
Is there a better way to run many processes like INSERT or UPDATE without looping through the information to be INSERT-ed or UPDATE-ed?
示例(为了简洁起见,我没有使用准备好的语句):
Example (I didn't use prepared statement for brevity sake):
$myArray = array('apple','orange','grape');
foreach($myArray as $arrayFruit) {
$query = "INSERT INTO `Fruits` (`FruitName`) VALUES ('" . $arrayFruit . "')";
mysql_query($query, $connection);
}
推荐答案
选项1 实际上,您可以一次运行多个查询.
OPTION 1 You can actually run multiple queries at once.
$queries = '';
foreach(){
$queries .= "INSERT....;"; //notice the semi colon
}
mysql_query($queries, $connection);
这将节省您的处理时间.
This would save on your processing.
选项2
如果对同一张表的插入非常简单,则可以在一个查询中进行多次插入
If your insert is that simple for the same table, you can do multiple inserts in ONE query
$fruits = "('".implode("'), ('", $fruitsArray)."')";
mysql_query("INSERT INTO Fruits (Fruit) VALUES $fruits", $connection);
查询最终看起来像这样:
The query ends up looking something like this:
$query = "INSERT INTO Fruits (Fruit)
VALUES
('Apple'),
('Pear'),
('Banana')";
这可能是您想要的方式.
This is probably the way you want to go.
这篇关于将MySQL查询放入PHP循环是否不好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!