0

I want to pull something I query into an array.

SELECT * FROM `x`

There may be 1 result or 1,000 results. The columns will vary, I mean, I'd rather be vague than write a specific interpreter for each query, I'd rather the function determine the column names.

So what do I really want?

<?php
    $results = mysql::query("SELECT * FROM x");
    $holding = array();

    //Now we get the results.
    while ($row = mysql_fetch_assoc($results)) $holding[] = $row;
?>

Obviously this is not C#, but I'd like the equivalent. I want all of my results, retaining their column names, in an array so I can call holding[0]["Column"];

My C# code is as follows.

            if (connected)
        {
            MySqlCommand cmd = new MySqlCommand(query, conn);
            MySqlDataReader reader = cmd.ExecuteReader();

            while (reader.Read()){
                //The problem is here, I don't know how to add them to a list/array retaining column names etc..

            }
        }
0

1 Answer 1

5

If all you want to get all rows into an array you can do so by using Linq to DataTable:

var dt = new DataTable();
dt.Load(cmd.ExecuteReader());
var rows = dt.AsEnumerable().ToArray();

Then you have an array of DataRows, you can get a value of a particular column using the indexer of DataRow for example:

// value of the id column of first row
var value = rows[0]["id"];
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, just what I needed. Took a while to implement, as the return was from the method to push through to another method. Thanks!

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.