PHP -在多维数组中存储mysql_fetch_assoc

时间:2022-12-04 21:32:07

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

我真的很难相信你不能说$data[0][5],它比为位置指定字符串值更符合逻辑

3 个解决方案

#1


3  

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.

运行这段代码,看看它说什么。

#2


1  

If you used the mysqli extension instead of mysql you could use fetch_all() which is faster than filling the array in a loop. So your function only needs to return the result of fetch_all()

如果使用mysqli扩展而不是mysql,可以使用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

#3


0  

Maybe I'm wrong, if all this happens in config.php, but I think, yu miss a few steps:

如果这一切都发生在配置中,我可能错了。php,但我想,余小姐有几个步骤:

Create connection:

创建连接:

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

Select database:

选择数据库:

mysql_select_db("mydbname");

After this, comes the mysql_query. But you say there are no warnings, so I assume, you do all this.

然后是mysql_query。但是你说没有警告,所以我假设,你做了所有这些。

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;
}

#1


3  

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.

运行这段代码,看看它说什么。

#2


1  

If you used the mysqli extension instead of mysql you could use fetch_all() which is faster than filling the array in a loop. So your function only needs to return the result of fetch_all()

如果使用mysqli扩展而不是mysql,可以使用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

#3


0  

Maybe I'm wrong, if all this happens in config.php, but I think, yu miss a few steps:

如果这一切都发生在配置中,我可能错了。php,但我想,余小姐有几个步骤:

Create connection:

创建连接:

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

Select database:

选择数据库:

mysql_select_db("mydbname");

After this, comes the mysql_query. But you say there are no warnings, so I assume, you do all this.

然后是mysql_query。但是你说没有警告,所以我假设,你做了所有这些。

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;
}