Ben Pearce
Ben Pearce

Reputation: 7094

Parsing Array in PHP based on Key Values

Basic php question here. The following SQL code returns an array containing a key called 'date'. All I want to do is parse the 'date' value based on the key name. Any help?

$result = mysql_query("SELECT * FROM `table` WHERE columnName ='value'") or die(mysql_error());
 $data = array();
while ( $row = mysql_fetch_assoc($result) )
{
  $data[] = $row;
}
echo $data->{'date'}

Upvotes: 0

Views: 5119

Answers (4)

Ares
Ares

Reputation: 5903

mysql_fetch_assoc returns an ASSOCiative array. Which means it returns an array with your table name fields as keys. For example if your table has 3 columns 'date', 'name', and 'color'

Then you would access those fields in the following way.

$result = mysql_query("SELECT * FROM `table` WHERE columnName ='value'") or die(mysql_error());
 $data = array();

while ( $row = mysql_fetch_assoc($result) )
{
  echo $row['date']; //Prints the rows date field
  echo $row['name']; //Prints the row name field and so on.
}

Upvotes: 0

Tommaso Belluzzo
Tommaso Belluzzo

Reputation: 23685

foreach($data as $key => $value)
{
    if ($key == 'date')
    {
        echo "Date Value: '".$value."'";
        // Do your stuffs...
        echo "Date Final Value: '".$value."'";
    } 
}

Upvotes: 0

John Conde
John Conde

Reputation: 219864

You're using object syntax on an array which you can't do.

 echo $data['date'],

Upvotes: 1

Aman Virk
Aman Virk

Reputation: 3977

Ok here you go

With Foreach

foreach($data as $key => $value)
{
   if($key == 'date')
   {
      // do you parsing stuff
   }
}

Without foreach

$parsing_date = $data['date'];

Upvotes: 1

Related Questions