Pulling data from a Mysql table field and putting it into an array
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);
source to share
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']
source to share
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);
source to share