Home  >  Article  >  Backend Development  >  PHP solves an infinite loop caused by compressed code_PHP tutorial

PHP solves an infinite loop caused by compressed code_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 17:18:481041browse

test.table1表
id str1 str2
1 saa bbb
2 saa bbc
3 sss 123

Requirement: List the contents of the "str1" segment without duplication.


Originally it was very simple and only took a few lines, but I thought the code could be compressed a bit so that it looked more condensed, so something went wrong. The error code was as follows:

<?php
mysql_select_db("test", mysql_connect("localhost","******","******"));

while($row = mysql_fetch_array(mysql_query("SELECT DISTINCT str1 FROM table1")))
{
	echo $row['str1'];
	echo "<br>";
}
?>

Did you see the problem at first glance? This thing actually caused an endless loop. . . T_T

So I restored it step by step, and the infinite loop disappeared again. Obviously it is not a problem with the submission statement, but a problem with the grammatical structure.

Sure enough, the problem lies in while. Mysql_query will be executed every time a condition is detected. Then it was a mess.

Just make sure that mysql_query is executed only once. The correct code is as follows:

<?php
mysql_select_db("test", mysql_connect("localhost","******","******"));

$result = mysql_query("SELECT DISTINCT str1 FROM table1");
while($row = mysql_fetch_array($result))
{
	echo $row['str1'];
	echo "<br>";
}
?>

Optimizing code is the worst of all evils... Everyone, calm down, calm down!

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/621611.htmlTechArticletest.table1 table id str1 str2 1 saa bbb 2 saa bbc 3 sss 123 Requirement: No duplicate listing of "str1 "The content of the paragraph. It was originally very simple and only took a few lines, but I think the code can be compressed...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn