Pulling data from a Mysql table field and putting it into an array

I can find many tutorials showing you how to load an array into a database field, but it can't seem like you need to pull each field entry into the array as separate items. Seems to be simple enough can't get it to work, any help?

0


source to share


5 answers


If you are using the modern PDO library, use PDOStatement->fetchAll()

with the option fetch_style

set to PDO::FETCH_COLUMN

.

Based on the sample from this page:

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

      



If old MySQL API is used (not recommended, example excludes error checking)

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

      

+1


source


$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 this I think

0


source


after reading his question a few times, I think 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 exactly he wants ...

0


source


My interpretation of this question is that the questioner has inserted multiple rows into the table and is not sure how to handle them except one at a time. (Perhaps this question could also mean data serialized and then stuck in one field ... but I hope not!)

So, here's how to get multiple lines:

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

      

You will now have all the strings returned by your query in $data

, so something like this will work to access it:$data[2]['field1']

0


source


The examples below assume your operator SELECT

is stored in $select

and your connection is stored in $db

. The two-dimensional array of results is then saved in $rows

.

If you use mysql

(for procedures, mysqli

just replace mysql_

with mysqli_

):

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

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

      

Using classes mysqli

:

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

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

$result->close()

      

Usage PDO

:

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

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

      

0


source







All Articles