tags:

views:

606

answers:

5

I can find lots of tutorials showing you how to load an array into a database field but can't seem to figure out how to pull each entry in a field into an array as seperate items. Seems simple enough just can't get it to work, any help?

A: 
$big_2_dimensional_array_of_data;

foreach ($big_array_of_data as $row) {
  $query = "INSERT INTO table_name (field1, field2, ...) VALUES($row[0], $row[1], ...)
  mysql_query($query);
}

Something like that I think

Sergey Kuznetsov
wrong way around - I believe he wants to SELECT data, not INSERT it.
Alnitak
+1  A: 

If using the modern PDO library, use the PDOStatement->fetchAll() function with the fetch_style parameter set to PDO::FETCH_COLUMN.

Based on a sample from that page:

$sth = $dbh->prepare("SELECT field FROM dbtable");
$sth->execute();
$array = $sth->fetchAll(PDO::FETCH_COLUMN);

If using the old MySQL API (not recommended, example omits error checking)

$array = array();
$result = mysql_query("SELECT field FROM dbtable");
while ($row = mysql_fetch_row($result)) {
     $array[] = $row[0];
}
mysql_free_result($result);
Alnitak
A: 

after reading his question a few times, i guess what he wants to do is something like this:

$query = "SELECT field1, field2, ... fieldn FROM table;";
$r = mysql_query($query,$conn);
$row = mysql_fetch_assoc($r);

i'm still not quite sure what it is he exactly wants...

fly.floh
A: 

My interpretation of this question is that the questioner has inserted a number of rows into a table, and isn't sure how to handle getting them out other than one at a time. (It's possible that the question might also be referring to data serialized and then stuck into a single field... but I hope not!)

So, here's how to get multiple rows:

$query = "SELECT field1, field2, ... fieldn FROM table;";
$r = mysql_query($query,$conn);
$data = array();
while($row = mysql_fetch_assoc($r)) {
    $data[] = $row;
}

You'd now have all the rows returned by your query in $data, so something like this would work to access it: $data[2]['field1']

David
A: 

The examples below assume your SELECT statement is stored in $select and your connection is stored in $db. A two-dimensional array of the results is stored in $rows afterward.

If you're using mysql (for mysqli procedures, just replace mysql_ with mysqli_):

$result = mysql_query($select, $db);

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

Using mysqli classes:

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

$rows = [];
while ($row = $result->fetch_assoc()) {
    $rows[] = $row;
}

$result->close()

Using PDO:

$stmt = $db->query($select);
$stmt->execute();

$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
Ben Blank