[英]Getting rows from a database query into an array in CodeIgniter
So I have the following database table called "relacionproveedorfamilia" 因此,我有以下数据库表,称为“ relacionproveedorfamilia”
-----------------------------
| idProveedor | idFamilia |
-----------------------------
| 5 | 1 |
-----------------------------
| 5 | 2 |
-----------------------------
| 6 | 2 |
-----------------------------
I use a function where I provide the value for idProveedor and it should return an array with the idFamilia values that belong to the provided idProveedor. 我使用的函数为idProveedor提供值,它应该返回一个数组,该数组包含属于提供的idProveedor的idFamilia值。
For example, this is the query to get all idFamilia for idProveedor = 5 例如,这是获取idProveedor = 5的所有idFamilia的查询
SELECT idFamilia FROM relacionproveedorfamilia WHERE idProveedor = 5;
The result of the query is: 查询的结果是:
---------------
| idFamilia |
---------------
| 1 |
---------------
| 2 |
---------------
I am trying to get the query result into an array, so I can display the contents in my view. 我试图将查询结果放入数组中,以便可以在视图中显示内容。
In my model Proveedormodel I have the following function, which I've coded by checking other similar questions in this site. 在我的模型Proveedormodel中,我具有以下功能,通过检查此站点中的其他类似问题进行了编码。
public function obtenerIdFamiliaProveedor($idProveedor){
$query = $this->db->select('idFamilia')->from('relacionproveedorfamilia')->where('idProveedor', $idProveedor);
$arrayFamilias = array();
while($row = mysql_fetch_assoc($query)){
$arrayFamilias[] = $row;
}
return $arrayFamilias;
}
But in my view I am getting the error message: 但是在我看来,我收到了错误消息:
Message: mysql_fetch_assoc() expects parameter 1 to be resource, object given
How could I fix this? 我该如何解决?
You are mixing codeigniter Query builder class with mysql_ functions. 您正在将codeigniter查询构建器类与mysql_函数混合使用。 Why are you doing this?
你为什么做这个?
You have to change your code: 您必须更改代码:
while($row = mysql_fetch_assoc($query)){
to this: 对此:
foreach ($query->result_array() as $row)
And you need to add get
method at the end of your query: 并且您需要在查询末尾添加
get
方法:
$query = $this->db->select('idFamilia')->from('relacionproveedorfamilia')->where('idProveedor', $idProveedor)->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.