Allenph
Allenph

Reputation: 2015

Get an array of rows from a MySQL query?

I have this code...

$results_query = "SELECT * FROM profile WHERE string LIKE '%" . $search_deliminator . "%'";
$results_result = $database->query($results_query);
$result = mysql_fetch_array($results_result);

What I'm trying to do is pull all the rows in which the string column contains my search deliminator. Further, I would like to get the values from each column of the rows.

How would I pull the multidimensional array I need containing each row, and each value of each column within each row?

EDIT:

I'm looking to do something to this effect...

while ($row = mysql_fetch_assoc($results_result)) {

    $result[] = $row;

}

Then echo each column like this...

foreach ($result as $row) {
    echo $row["0"];
}

Upvotes: 2

Views: 935

Answers (3)

SteveTz
SteveTz

Reputation: 242

try this

$i=0;
while ($row = mysql_fetch_assoc($results_result)) {

 $result[$i]["column1"] = $row["column1"];
 $result[$i]["column2"] = $row["column2"];
 $i++;
}

To display the output use:

foreach ($result as $row) {
 echo $row["column1"];
 echo $row["column2"];
}

Upvotes: 1

Barmar
Barmar

Reputation: 782305

If you use PDO, you can use the fetchAll() method:

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

With mysql or mysqli, you use a loop:

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

Upvotes: 2

Stuart Wagner
Stuart Wagner

Reputation: 2067

To get a flattened array of the result set, try this:

$result = array();

while ($row = mysql_fetch_assoc($results_result)) {
    $result[$row['id']] = $row;
}

echo json_encode($result);

Also, you should look into either MySQLi or PDO to replace the (now deprecated) MySQL extension.

Upvotes: 5

Related Questions