我在CI模型中创建了一个函数,它首先查询表以获取其字段(因为这些字段会随着时间的推移而动态变化,因此我无法对字段名称列表进行硬编码),然后何时它获取第一个查询的结果,并构建一个字段名称列表,它再次查询该表以获取属于一行或记录的值。然后将第二个查询结果存储在一个数组中,该数组被传递回控制器。这是完成这些步骤的完整功能:
public function getAssetFeatures($as_id)
{
$data = array();
//this sql query gets the field names from the table I want to query.
$sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '".DATABASE."' AND TABLE_NAME = 'as_features';";
$query = $this->db->query($sql);
$count = 0;
foreach($query->result_array() as $k)
{
foreach($k as $kk=>$v)
{
if( $v != "as_features_id" &&
$v != "as_id" &&
$v != "cid" &&
$v != "lot_size" )
{
$features_array[$count] = $v;
$count++;
}
}
}
$features_string = implode(",",$features_array);
//I got the field names, put them into an array, then concatenated them into a string, which I will use for the fields in the next query:
$sql = "SELECT $features_string FROM as_features WHERE as_id='$as_id'";
$query = $this->db->query($sql);
//mandatory rooms/features:
foreach($query->result() as $row)
{
foreach($row as $k=>$v)
{
$data["$k"] = $v; //build an associative array with the values of each field for the one row I am querying
}
}
return $data; // return the associative array.
}
起初我觉得在我的表或视图中有些东西被打破了,但是由于我通过刷新页面并输入完全相同的值继续重复对模型函数的相同调用,我注意到有时候代码工作了,我不会#39; t得到错误"未定义索引"。
所以我用这段代码输出了数组的结果:
echo "<pre>";
print_r($asset['features']);
echo "</pre>";
...并且预期输出有时会成功执行,但不是所有时间,对于使用完全相同的参数的完全相同的操作,如下所示:
Array
(
[kitchen] => 1
[liv_area] => 0
[dining] => 1
[family] => 0
[bed] => 0
[bath] => 1
[half_bath] => 0
[parking] => 0
[car_storage] => 0
[pool] => 0
[miscellaneous] => 0
)
当查询返回结果集然后返回填充的数组时,我的表单工作并且看起来正常。但是,大多数情况下查询失败,我得到如下所示:
答案 0 :(得分:1)
问题在于以下代码片段:
foreach($query->result() as $row)
{
foreach($row as $k=>$v)
{
$data["$k"] = $v; //build an associative array with the values of each field for the one row I am querying
}
}
它的工作方式是,对于返回的每个结果,它将使用相关键覆盖$data
。但是,因为$query->result()
将返回您想要的行,然后返回false,该数组本质上最终为:
$data[] = false;
,即将整个数组设置为false / empty。
如果将循环更改为,则不会对$query->result()
的错误值执行循环内的代码:
while ($row = $query->result())
{
// your code
}
值得注意的是,如果你打算从中返回更多的那一行,它将无法工作,因为它只会覆盖现有的值。
答案 1 :(得分:0)
好的,问题是我的代码,而不是查询。我传递了一个加密的as_id
,但在构造select查询之前忽略了它的解密。这就是为什么它有时会起作用,而不是其他的。出于某种原因,MySQL允许加密的as_id
匹配INT类型的现有as_id。执行解密后,查询结果变得可预测。这是我不希望SO成员具有神圣性的东西。感谢。
public function getAssetFeatures($as_id)
{
$as_id = $this->utilityclass->decryption9($as_id); // <- I had this commented out. In fact, I removed the line from my example code in the original post, because I didn't think it was important to the question. Not only was it important, it was the problem!
$data = array();
$sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '".DATABASE."' AND TABLE_NAME = 'as_features';";
$query = $this->db->query($sql);