Jump to content

Creating PHP array from MySQL


Mutley

Recommended Posts

Hi guys,

 

I've got this:

<?php
$aUsers = array(
	"Ädams, Egbert",
	"Altman, Alisha",
	"Archibald, Janna",
	"Auman, Cody",
	"Bagley, Sheree",
	"Ballou, Wilmot"
);
?>

 

But I wish to pick the entries up from the database, like the below example, except it doesn't work as I'm assiging a variable to it, just creates a parse error:

 

<?php
$aUsers = array(
$sql  = "SELECT id, zip FROM zipcodes ORDER BY id";
$result = mysql_query($sql);
while(list($id, $zip) = mysql_fetch_row($result)) {
	echo '"'.$id.", ".$zip.'"'.',<br />';
}
);
?>

 

Any thoughts? I know the query I do creates an array anyway I think, just don't know how to get it into the desired format.

 

Thanks,

Nick.

Link to comment
https://forums.phpfreaks.com/topic/139346-creating-php-array-from-mysql/
Share on other sites

<?php
   $sql  = "SELECT id, zip FROM zipcodes ORDER BY id";
   $result = mysql_query($sql);
   while(list($id, $zip) = mysql_fetch_row($result)) {
      $aZips[] = array(
        "id" => $id,
        "zip" => $zip,
      );
   }
?>

 

or

 

<?php
   $sql  = "SELECT id, zip FROM zipcodes ORDER BY id";
   $result = mysql_query($sql);
   while(list($id, $zip) = mysql_fetch_row($result)) {
      $aZips[$id] = $zip;
   }
?>

 

(you can't have any code within array() )

<?php
   $sql  = "SELECT id, zip FROM zipcodes ORDER BY id";
   $result = mysql_query($sql);
   while(list($id, $zip) = mysql_fetch_row($result)) {
      $aUsers[$id] = $zip; 
   }

print_r($aUsers);
?>

 

Maybe that is what you are looking for.

Are you sure you had data in your database? And that you have a valid SQL connection?

 

<?php
   $sql  = "SELECT id, zip FROM zipcodes ORDER BY id";
   $result = mysql_query($sql) or die(mysql_error());
   while($row = mysql_fetch_row($result)) {
      $aUsers[$row['id']] = $row['zip']; 
   }

print_r($aUsers);
?>

 

That should work as long as you have a valid connection and data in the database.

Cheers guys, got that working! Just 1 more thing, is it possible to create 2 arrays with an INNER JOIN?

 

<?php

   $sql  = "SELECT streets.id, streets.street zipcodes.zip FROM streets INNER JOIN zipcodes ON streets.zip = zipcodes.id ORDER BY streets.id";
   $result = mysql_query($sql);
   while(list($id, $street, $zip) = mysql_fetch_row($result)) {
      $aUsers[$id] = $street;
  $aInfo[$id] = $zip;
   }

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.