I have this method in my db class

我的db類中有這個方法

public function query($queryString)

{

if (!$this->_connected) $this->_connectToDb(); //connect to database

$results = mysql_query($queryString, $this->_dbLink) or trigger_error(mysql_error());

return mysql_num_rows($results) > 0 ? mysql_fetch_assoc($results) : false;

}

This works great for queries that return 1 row, but how can I get an array returned something like this?

這適用於返回1行的查詢,但是如何才能獲得返回類似的數組呢?

$array[0]['name'] = 'jim'

$array[0]['id'] = 120

$array[1]['name'] = 'judith'

$array[1]['ID'] = 121

Now I know I could use a while loop to insert this data into the array like so, but I was wondering if PHP could do this with an internal function? I havn't been able to find on the docs what I'm after.

現在我知道我可以使用while循環將這些數據插入到數組中,但我想知道PHP是否可以使用內部函數執行此操作?我無法在文檔上找到我所追求的內容。

The reason I don't want to run the while within the method is because I am going to reiterate back over the array when it's returned, and I'd rather not run through the results twice (for performance reasons).

我不想在方法中運行while的原因是因為我將在返回時重復數組,並且我不想兩次運行結果(出於性能原因)。

Is there a way to do this? Do I have a problem with my general query method design?

有沒有辦法做到這一點?我的常規查詢方法設計有問題嗎?

Thank you muchly!

非常感謝你!

5 个解决方案

#1

4

public function query($queryString)

{

if (!$this->_connected) $this->_connectToDb(); //connect to database

$results = mysql_query($queryString, $this->_dbLink) or trigger_error(mysql_error());

$data = array();

while($row = mysql_fetch_assoc($results))

{

$data[] = $row;

}

return $data;

}

this will always return an array.

這將始終返回一個數組。

EDIT: I didn't read the question well. If you realy don't want to use the loop then I would do this:

編輯:我沒有很好地閱讀這個問題。如果你真的不想使用循環,那么我會這樣做:

public function query($queryString)

{

if (!$this->_connected) $this->_connectToDb(); //connect to database

return mysql_query($queryString, $this->_dbLink) or trigger_error(mysql_error());

}

then loop over it, however I would just use the loop.

然后循環它,但我只是使用循環。

#2

2

You might also want to look at the PDO extension. You can load the entire result set into an array or you can loop using foreach.

您可能還想查看PDO擴展。您可以將整個結果集加載到數組中,也可以使用foreach循環。

$db = new PDO($connection_string, $username, $password);

$result = $db->query($queryString);

foreach($result as $row) {

// do something

}

// or

$result = $db->query($queryString);

$result_array = $result->fetchAll(PDO::FETCH_ASSOC);

?>

#3

1

Most people use a while() loop in the query to do exactly what you want and then loop over the array to process it.

大多數人在查詢中使用while()循環來完成您想要的操作,然后遍歷數組來處理它。

However, you're right: it wastes memory, which could be a problem with a large dataset. An alternative is for your query method to return the resultset resource. Then your while loop can use that to fetch each row as it requires it.

但是,你是對的:它浪費了內存,這可能是一個大數據集的問題。另一種方法是讓查詢方法返回結果集資源。然后你的while循環可以使用它來獲取它所需的每一行。

To abstract that away, I would suggest another class to do that for you. Then your query call would return a new instance of that class which has the MySQL resultset resource as an instance variable and packages up the mysql_fetch_assoc() call.

為了抽象出來,我會建議另一個班為你做這件事。然后,您的查詢調用將返回該類的新實例,該實例將MySQL結果集資源作為實例變量並打包mysql_fetch_assoc()調用。

#4

0

Look at PEAR::MDB2 (Quickstart Cheatsheet). It provides lots of different functions for doing something like this. It also does not tie you down into using MySQL specific functions because it is a database abstraction layer.

看看PEAR :: MDB2(Quickstart Cheatsheet)。它提供了許多不同的功能來做這樣的事情。它也不會限制你使用MySQL特定的功能,因為它是一個數據庫抽象層。

$result = $db->queryRow($query, MDB2_FETCHMODE_ASSOC);

$ result = $ db-> queryRow($ query,MDB2_FETCHMODE_ASSOC);

There are other abstraction layers such as ADO as well.

還有其他抽象層,如ADO。

#5

0

thanks for the ideas. I have a function that returns an associative array from the sql (used in Moodle).

謝謝你的想法。我有一個函數,從sql返回一個關聯數組(在Moodle中使用)。

$results = get_records_sql($sql);

$ results = get_records_sql($ sql);

//to create a numerically indexed array:

$data = array();

foreach ($results as $row)

{

$data[] = $row;

}

return $data;

}

php 返回索引,PHP mySQL - 你能否返回帶有數字索引的關聯數組?相关推荐

  1. oracle索引与mysql区别_MySQL和Oracle中的唯一性索引从差别(r12笔记第83天)

    今天在修复MySQL数据的时候,发现一个看起来"奇怪"的问题. 有一个表里存在一个唯一性索引,这个索引包含3个列,这个唯一性索引的意义就是通过这3个列能够定位到具体1行的数据,但是 ...

  2. mysql性能优化-慢查询分析、优化索引和配置

    目录 一.优化概述 二.查询与索引优化分析 1性能瓶颈定位 Show命令 慢查询日志 explain分析查询 profiling分析查询 2索引及查询优化 三.配置优化 1)      max_con ...

  3. MySQL 搜索指定时间范围数据, 时间字段有索引但是还是很费时

    问题分析 所遇情况: 数据库版本:5.6.38 查询时使用时间类型,在status.closed.playback_state字段上都有索引 几种查询语句 explain (select count( ...

  4. in会让mysql索引失效吗_mysql的in会不会让索引失效?

    mysql的in会让索引失效吗?不会! 看结果: mysql> desc select * from tb_province where name in ('lily3', 'lily2', ' ...

  5. mysql存储过程更新数据后返回一个字段_史上最全存储引擎、索引使用及SQL优化的实践...

    整个MySQL Server由以下组成 : Connection Pool :连接池组件 Management Services & Utilities :管理服务和工具组件 SQL Inte ...

  6. php mysql只获取一条数据_php mysql 查询只返回第一条数据

    php mysql 查询只返回第一条数据 $search = mysql_query("select * from `info`"); $search = mysql_fetch_ ...

  7. R语言str_subset函数和str_which函数:str_subset函数提取字符串向量中所有包含匹配字符的字符串、str_which函数返回字符串向量中所有包含匹配字符的位置(索引)

    R语言str_subset函数和str_which函数:str_subset函数提取字符串向量中所有包含匹配字符的字符串.str_which函数返回字符串向量中所有包含匹配字符的位置(索引) 目录

  8. mysql存储过程的返回值在哪里设置_MySQL存储过程的返回值

    我必须创建一个SP,如果它有效,则返回一个值.但它不返回任何东西,我不知道,为什么? CREATE DEFINER=`root`@`localhost` PROCEDURE `validar_egre ...

  9. Leetcode 给定一个数组,给定一个数字。返回数组中可以相加得到指定数字的两个索引

    问题内容是:给定一个数组,给定一个数字.返回数组中可以相加得到指定数字的两个索引. 比如:给定nums = [2, 7, 11, 15], target = 9 那么要返回 [0, 1],因为2 + ...

最新文章

  1. SAP 系统中STO+VC 技术实现
  2. Flutter一切皆widget但是不要将所有东西放入一个widget
  3. matlab有向图分割算法,基于万有引力搜索算法图像分割的MATLAB实现
  4. java对import语句_Java的import语句 - 不积跬步,无以至千里 - 51Testing软件测试网 51Testing软件测试网-软件测试人的精神家园...
  5. Android 引用模块中的类,解决Android项目中找不到Module中的封装类或引用的第三方类库...
  6. transaction缩写为什么是tx_TX Transaction locks常见的4种情况
  7. I.MX6 dhcpcd 需要指定网卡
  8. 一文细数73个Vision transformer家族成员
  9. Java调用OpenDDS(2)-理解OpenDDS自带的Messager示例
  10. centeros 下载及安装
  11. win10引导安卓x86_手把手教你在电脑上安装安卓x86版+win10的双系统(只能在能用微软电脑系统的平板上安装)...
  12. 【C系列】How to printf “unsigned long” in C?
  13. JZOJ 3337. 【NOI2013模拟】wyl8899的TLE【暴力】
  14. C语言实现AES ecb加解密
  15. Word 2016 公式编辑器中微分符号的竖线(2018.5.17)
  16. SAP_HCM_Schema_CN28_XIN0
  17. cesium中级(二)获取地形高度
  18. 信息时代碎片化学习的理解
  19. vivado报位置约束指令的critical warning
  20. SQL SERVER 2008 R2 错误代码 17000 - 17999

热门文章

  1. java outputstream api,Java8 stream API以及常用方法
  2. 只可顺守不可逆取书法_坚持练书法10年以上,会怎么样?
  3. java 安卓 html文件怎么打开方式_android 浏览器 打开本地html文件的方法
  4. 腾讯云linux配置服务器配置,centos7+腾讯云服务器搭建wordpress
  5. 讯飞输入法pad版x86_讯飞搜狗为何抵不过百度输入法?读完你就明白了
  6. 设置android 触摸灵敏,3D Press触屏灵敏度设置教程 魅族PRO 6 3D Press触控力度怎么调...
  7. 用python进行因式分解_python中怎么对一个数进行因式分解?
  8. python从大到小排序_python作业:用嵌套的列表存储学生成绩数据,并编程完成如下操作...
  9. 免校准的电量计量芯片_单相电能表如何校准(单相电能计量芯片+MCU)
  10. C++安全方向(三):3.2 单项散列函数的应用场景