0

I'm trying to build a re-usable function to multidimansional array for every tablename i put in. Like most i start mine tables whit ID and want to start the array whit that id, so not start whit 0 :) . foneticly--> $my_array[id]["email"]

So to build it i thought "what do i need" and found : $count_colum, $total_row an ofcource the data itself.

I know how to build a array, but i dont know how to build a "variable" array. I also know i cant use PHP inside a array :) (whish would help iff you tell me)
$my_array = array( $row['id'] for ($i = 0; $i < $count_colum; $i++){...} I also hope somebody knows what i mean :) I'm a little bit new to this all ;)

This is what i get this far:

function make_MDA($tablename)
{
    $dbh = new PDO("mysql:host='localhost';dbname='dbname', 'usr','pas'");
    $query = $dbh->prepare("SELECT * FROM `".$tablename."`"); 
    $query->execute();

    $count_colum = $query->columnCount();
    $result = $query->fetchAll();
    $total_row = count($result);

    for ($i = 0; $i < $count_colum; $i++) 
    {
        $meta = $query->getColumnMeta($i);
        $column[] = $meta['name'];
    }
    foreach ($result as $row)
    {
        $my_array = array( $row['id'] //this is where I'm stuck
    }
//        echo $column[3];
//        echo $total_row;
//        echo $count_colum;
}

1 Answer 1

1

This should work, don't overcomplicate things:

function make_MDA($tablename)
{
    $dbh = new PDO("mysql:host='localhost';dbname='dbname', 'usr','pas'");
    $query = $dbh->prepare("SELECT * FROM `".$tablename."`"); 
    $query->execute();

    $result = $query->fetchAll();

    foreach ($result as $row)
    {
        $id = $row['id'];
        $my_array[$id] = $row; 
    }

    return $my_array;
}

I would make the connection to the database $dbh once outside this function.

Sign up to request clarification or add additional context in comments.

2 Comments

thnx, this totaly worked.... +1 4 U :) btw why would you do the $dbh once outside this function?
So you can reuse the connection multiple times with this function for different database tables. Similar reason as to why you make functions. You need to know that building a database connection is a costly process. It takes time and resources.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.