简体   繁体   English

数组在PHP中返回相同的值

[英]Array Returning the same value in PHP

  $result = mysql_query("SELECT position
        FROM ".$this->table_name."
        WHERE c_name = '".$chName."'");

        while($row = mysql_fetch_array($result)) 
        {
            return(array($row['position']));
        }

I am getting the same value, even if i change the combox... i need the ID of the combox box when its changed. 即使更改combox,我也得到相同的值...更改时,我需要combox的ID。 But for every time i select it displays the same value. 但是对于每次我选择它都会显示相同的值。

function getID($chName) {

}

chName is the value i am getting from combo box from Flex. chName是我从Flex的组合框中获得的值。

You are always returning just the first row. 您总是只返回第一行。 Maybe you want the whole data set and not just the first record. 也许您想要整个数据集,而不仅仅是第一条记录。 So try this: 所以试试这个:

$result = mysql_query("SELECT position
    FROM ".$this->table_name."
    WHERE c_name = '".$chName."'");
$retVal = array();
while ($row = mysql_fetch_array($result)) {
    $retVal[] = $row['position']);
}
return $retVal;

why 为什么

 return(array($row['position']));

and not just 而不仅仅是

return($row['position']);

For any other help you have to provide more informationn (hmtl? output?) 对于任何其他帮助,您必须提供更多信息(hmtl?输出?)

Gumbo's answer is correct. 浓汤的答案是正确的。

Notice that unconditionally returning something inside a loop makes the loop itself to be run only once . 请注意,无条件返回循环内的某些内容会使循环本身运行一次 This is true in general and you should always avoid such a monster :) 通常这是对的,您应该始终避免使用这种怪物:)

If you are a memory saver guy you do a very little memory an CPU improvement: 如果您是节省内存的人,那么您会在CPU方面做很少的改进:

mysql_fetch_assoc()

that avoids retrieving an integer indexed array you'll not use 避免检索您不会使用的整数索引数组

Dont use double quotes if you arent wanting variables inside parsed. 如果您不希望在变量内部进行解析,请不要使用双引号。

$results = array();

// Dont forget you should be escaping $chName
$result = mysql_query("SELECT `position` FROM `{$this->table_name}` WHERE `c_name` = '$chName';");

while($row = mysql_fetch_array($result)) 
{
    $results[] = $row['position'];
}

return $results;

Or 要么

$results = array();

// Dont forget you should be escaping $chName
$result = mysql_query('SELECT `position` FROM `'.$this->table_name.'` WHERE `c_name` = \''.$chName.'\';');

while($row = mysql_fetch_array($result)) 
{
    $results[] = $row['position'];
}

return $results;

The other folks have posted good answer; 其他人都发表了很好的答案。 Just one suggestion - code a DB wrapper class so you don't have to manually fetch arrays all the time, which is a source of constant error. 只是一个建议-对数据库包装器类进行编码,因此您不必一直手动获取数组,这是不断出错的来源。 I have my own Query class and after performing a query, I just do $query->dumpResultAsArray() and do the for-each from there. 我有自己的Query类,执行查询后,我只需要执行$ query-> dumpResultAsArray()并从那里进行for-each。

It's less efficient, but it's more robust and easier to debug. 它的效率较低,但更健壮且更易于调试。

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

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