跳过循环中的错误? (PHP)
我有一个循环,代码循环,在每个循环中它连接到不同的服务器,然后进行 MySQL 查询。然而,有时循环/查询之一无法到达末尾,并且所有代码都会中断。有没有办法,如果循环出现错误,则跳过进程/移至下一个循环?
I have a loop where the code loops and in every loop it connects to different server and then makes MySQL query. However sometimes one of the loops/queries cannot reach to the end and all the code breaks. Is there a way where if the loop gives error then skip the processes / move to next loop?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
正如上面的评论所述,执行此操作的正确方法是在
try...catch
块中。要了解有关这些内容的更多信息,您可以在此处阅读相关内容。
谢谢@保罗。
As stated in the comments above, the correct way to do this is within a
try...catch
block.To learn more about these, you can read about them here.
Thanks @Paul.
在该循环内,检查连接,如果已建立,则执行逻辑。因此,如果没有建立连接,逻辑部分将被跳过。
Inside that loop ,check the connection and if it is made, do the logic. So that if connection is not made, the logic part would be skipped.
使用“继续”跳到循环中的下一项:
继续
Use "continue" to skip to the next item in hte loop:
continue
这一切都取决于您是否使用 php 的内置 mysql、mysqli 或某些第三方库。但作为一般规则,我会推荐以下逻辑。
根据您在相关表上所做的工作,您还可以使用 @ 前缀(例如 @mysql_query)来抑制查询中的任何错误然后检查受影响的行数。如果你进行选择,你可以检查你的结果集,看看你是否得到了任何返回等。不过,我不喜欢使用 @ ,应该注意的是,从现有表中进行选择为空,类似的情况可能会导致奇怪的行为,具体取决于您的代码。 Try/Catch 是处理错误控制流的更好方法。但相比之下,实际上抛出异常是一个相当慢的过程,并且由于所有工作都围绕着连接到各处的数据库,因此如果此循环可能抛出大量异常,那么进一步减慢速度可能不是一个好主意。此外,当使用它跳过循环中的某个步骤时,某些人可能很难遵循逻辑。因此,像 @ 这样的东西在这里是可以接受的;)
This all depends on if you use php's built-in mysql, mysqli or some third party library. But as a general rule I would recommend the following logic.
Depending on the work you do on the table in question you could also suppress any errors from your query using the @ prefix like @mysql_query and then check for number of affected rows. If you do a select you could check your result set to see if you got anything back etc. I don't like the use of @ though and it should be noted that a select from an existing table that was empty and similar situations could result in strange behavior depending on your code. Try/Catch is a nicer approach to handle error control flow. But actually throwing an exception is quite a slow process in comparison and since all the work revolves around connecting to databases all over the place it might not be a good idea to slow it down even more if a lot of exceptions could be thrown by this loop. Also, when using it to skip a step in a loop it can be quite hard for some people to follow the logic. Therefore something like @ could be acceptable here ;)