Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Storing mysql_fetch_assoc in a multi-dimensional array

Tags:

php

mysql

I'm new to PHP, so I'm not exactly sure how it works.

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

like image 583
Ash Avatar asked Mar 19 '11 22:03

Ash


People also ask

What is the difference between mysql_fetch_array () and mysql_fetch_assoc ()?

What is the difference between mysql_fetch_object and mysql_fetch_array? Mysql_fetch_object returns the result from the database as objects while mysql_fetch_array returns result as an array. This will allow access to the data by the field names.

What will mysql_fetch_assoc () return?

Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead. mysql_fetch_assoc() is equivalent to calling mysql_fetch_array() with MYSQL_ASSOC for the optional second parameter. It only returns an associative array.

What does Mysqli_fetch_assoc () do in PHP?

The mysqli_fetch_assoc() function is used to return an associative array representing the next row in the result set for the result represented by the result parameter, where each key in the array represents the name of one of the result set's columns.

What are multidimensional array in PHP explain with example?

A multidimensional array is an array containing one or more arrays. PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people.


2 Answers

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
  • 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.

like image 174
Your Common Sense Avatar answered Oct 12 '22 09:10

Your Common Sense


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()

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
like image 21
Jon Black Avatar answered Oct 12 '22 09:10

Jon Black