简体   繁体   English

PHP中的神秘代码

[英]Mystery code in PHP

This chunk of code was found in a script someone else wrote that I was asked to edit. 在别人要求我编辑的脚本中找到了这段代码。 It doesn't appear to be doing anything.. I'm wondering why on earth it was there and if something somewhere in the world would go terribly wrong if I remove it.. 它似乎什么也没做。.我想知道为什么它在那里,如果我删除它,如果世界上某个地方会发生严重错误。

Am I missing something? 我想念什么吗?

//begin mystery code - i have no idea what this chunk of code is doing..
$result = mysql_query("SHOW COLUMNS FROM ".$table."");
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$i++;
}
}
//end mystery code

$result is not referenced anywhere else.. $result在其他任何地方均未引用。

It's counting the number of columns in a database table $table , and putting the value in $i 它计算数据库表$table的列数,并将值放入$i

Presumably, $i is used later for something? 大概, $i稍后用于某些东西吗?

It does two things: 它有两件事:

  1. Increasing $i per row. 每行增加$i
  2. Storing each row into $row and finally false into it. 将每一行存储到$row ,最后将false放入其中。

So finally it sets: 因此,最终它设置为:

  • $i to the number of rows. $i为行数。
  • $row to false $row false

But do not wonder about crap code much. 但是不要太在乎废话代码。 Improve it instead: 改进它:

$i   = mysql_num_rows($result);
$row = false;

Also encapsulate mysql_* calls so you can easily replace them later. 还封装mysql_*调用,以便您以后可以轻松替换它们。 You should also handle the error case if the query fails. 如果查询失败,您还应该处理错误情况。

only thing it seems to do is to count number of columns in $i. 似乎唯一要做的就是计算$ i中的列数。 If $i is not used anywhere in the script you can remove this code. 如果在脚本的任何地方都没有使用$ i,则可以删除此代码。

also look for $row and $result variable uses in the script if none code can be removed. 如果无法删除任何代码,还请在脚本中查找$ row和$ result变量使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM