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!
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!
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.
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];
Try:
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
printf("ID: %s Name: %s", $row["id"], $row["name"]); //or echo
}
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();
}