简体   繁体   English

PHP - 在多维数组中存储mysql_fetch_assoc

[英]PHP - Storing mysql_fetch_assoc in a multi-dimensional array

I'm new to PHP, so I'm not exactly sure how it works. 我是PHP的新手,所以我不确定它是如何工作的。

Anyway, I would line to return a multidimensional array to another method, essentially something storing a small amount of record and columns, table like structure. 无论如何,我会将多维数组返回到另一个方法,本质上是存储少量记录和列,类似于表的结构。

I've written the following, no warning but no data either 我写了以下内容,没有任何警告但也没有数据

public function GetData($sqlquery)
{
    include 'config.php';

    $result = mysql_query($sqlquery,$con);
    $data = array();

    while($row = mysql_fetch_assoc($result))
    {
        $data[] = $row;
    }

    return $data;
}

Most likely doing something stupid 最有可能做一些愚蠢的事情

Help appreciated. 帮助赞赏。

EDIT: 编辑:

Thanks for all the fast replies 感谢所有快速回复

I figured out why this wasn't working, I was addressing the array as such 我弄清楚为什么这不起作用,我正在解决这个问题

print $data[0][0];

Rather than 而不是

print $data[0]['title']; 

for example, thanks all :) 例如,谢谢所有:)

PS I really find it hard to believe you can't say $data[0][5], It's more logical IMO than specifying a string value for location PS我真的觉得很难相信你不能说$ data [0] [5],IMO比为位置指定一个字符串值更合乎逻辑

Your code seems okay. 你的代码似乎没问题。 At least, you're going in right direction. 至少,你正朝着正确的方向前进。

Just some minor corrections: 只是一些小的修正:

  • NEVER include config inside of a function. 永远不要在函数内部包含配置。 it should be done in class constructor 它应该在类构造函数中完成
  • if you really want to use connection identifier - make it class variable. 如果你真的想使用连接标识符 - 使它成为类变量。 But for most applications using single connection to db its unnecessary to use $con, so you can omit it 但对于大多数使用单连接到db的应用程序,不必使用$ con,因此可以省略它
  • error handling is absolutely necessary 错误处理是绝对必要的

so, 所以,

public function GetData($sqlquery)
{
    $data = array();
    $result = mysql_query($sqlquery) or trigger_error(mysql_error().$sqlquery);
    if ($result)
    {
        while($row = mysql_fetch_assoc($result))
        {
            $data[] = $row;
        }
    }
    return $data;
}

run this code and see what it says. 运行此代码并查看它的内容。

If you used the mysqli extension instead of mysql you could use fetch_all() which is faster than filling the array in a loop. 如果您使用mysqli扩展而不是mysql,则可以使用fetch_all(),这比在循环中填充数组更快。 So your function only needs to return the result of fetch_all() 所以你的函数只需要返回fetch_all()的结果

return $result->fetch_all(MYSQLI_ASSOC);

Script 脚本

<?php

ob_start(); 

try
{
    $db = new mysqli("localhost", "foo_dbo", "pass", "foo_db", 3306);

    if ($db->connect_errno) 
        throw new exception(sprintf("Could not connect: %s", $db->connect_error));

    $sqlCmd = "select * from users order by username";

    $startTime = microtime(true);

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

    if(!$result) throw new exception(sprintf("Invalid query : %s", $sqlCmd));

    if($result->num_rows <= 0){
        echo "no users found !";
    }
    else{

        $users = $result->fetch_all(MYSQLI_ASSOC); //faster 

        //while($row = $result->fetch_assoc()) $users[] = $row; //slower

        echo sprintf("%d users fetched in %s secs<br/>", 
            count($users), number_format(microtime(true) - $startTime, 6, ".", ""));

        foreach($users as $u) echo $u["username"], "<br/>";
    }
    // $result->close();
}
catch(exception $ex)
{
    ob_clean(); 
    echo sprintf("zomg borked - %s", $ex->getMessage());
}
//finally
if(!$db->connect_errno) $db->close();
ob_end_flush();
?>

Testing 测试

//fetch_all()

 1000 users fetched in 0.001462 secs
 5000 users fetched in 0.005493 secs
15000 users fetched in 0.015517 secs
50000 users fetched in 0.051950 secs
100000 users fetched in 0.103647 secs

//fetch_assoc plus loop

 1000 users fetched in 0.001945 secs
 5000 users fetched in 0.008101 secs
15000 users fetched in 0.023481 secs
50000 users fetched in 0.081441 secs
100000 users fetched in 0.163282 secs

Maybe I'm wrong, if all this happens in config.php , but I think, yu miss a few steps: 也许我错了,如果所有这些都发生在config.php ,但我想,你错过了几步:

Create connection: 创建连接:

$con = mysql_connect("localhost", "mysql_user", "mysql_password");

Select database: 选择数据库:

mysql_select_db("mydbname");

After this, comes the mysql_query . 在此之后,来了mysql_query But you say there are no warnings, so I assume, you do all this. 但是你说没有警告,所以我想,你做了这一切。

I would do something like this (there are better, more complex solutions): 我会做这样的事情(有更好,更复杂的解决方案):

include 'config.php'; // contains definition of $conf array

$con = mysql_connect($conf['host'], $conf['user'], $conf['pass']);
mysql_select_db($conf['db']);

function GetData($sqlquery)
{
    global $con;

    $result = mysql_query($sqlquery,$con);
    $data = array();

    while($row = mysql_fetch_assoc($result))
    {
        $data[] = $row;
    }

    return $data;
}

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

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