0

I'm trying to turn results from a query into an array.

turn this

$result = mysql_query("SELECT * FROM WHATEVER");

into

$result = array('id' => 1, 'name' => 'bob');

But I don't want print_r(), i want to echo php executable code.

Thanks!

jacoz
  • 3,508
  • 5
  • 26
  • 42

4 Answers4

2

Try with:

$records = array();
$query = mysql_query("SELECT * FROM WHATEVER ");
while ($result = mysql_fetch_assoc($query)) {
    $records[] = $result;
}

Now you can use $records as your (re-usable) array.

Please, don't use mysql_* functions in new code. They are no longer maintained and the deprecation process has begun on it. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

Zoe
  • 27,060
  • 21
  • 118
  • 148
jacoz
  • 3,508
  • 5
  • 26
  • 42
  • note that `mysql_fetch_assoc()` will return only one row, you have to keep it in a loop to get all of them – Ivan Hušnjak Nov 29 '12 at 22:29
  • I meant for unlimited records. But $result = mysql_fetch_assoc($query); will only work for that run, im trying to get an array i can run elsewhere. – Dan Herbert Nov 29 '12 at 22:42
1

You can use PDO and PDOStatement::fetchAll()

$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
$dbh = new PDO($dsn, $user, $password);
$sth = $dbh->prepare("SELECT * FROM WHATEVER");
$sth->execute();
$results = $sth->fetchAll(); // get all rows
var_dump($results);

//to get only first row:
$result = $results[0];
Ivan Hušnjak
  • 3,493
  • 3
  • 20
  • 30
0

Try:

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
 printf("ID: %s  Name: %s", $row["id"], $row["name"]); //or echo
}

Manual

Teena Thomas
  • 5,139
  • 1
  • 13
  • 17
-1

easy:

$result = mysql_query("SELECT * FROM WHATEVER ");
if($result)
{
$result = mysql_fetch_array($result,MYSQL_ASSOC);
/*
manipule $result according you need
*/
print_r($result);
}
else{
echo mysql_error();
}
chenio
  • 592
  • 3
  • 11
  • 27