Jump to content

Get data from database into variable


dreampho

Recommended Posts

Hi. I am new to PHP, and am testing a few things in a Expression Engine module.

 

I have a database called 'currency', and I want to retrieve some data from it and place the data into variables. How can I do this?

 

Here is what I currently have.

 

public function convert() {

 $price = $this->EE->TMPL->fetch_param('price');
 if( $price === FALSE ) {
	 return "";
 }

 $tagdata = $this->EE->TMPL->tagdata;

 $this->EE->db->select( "usd, eur, gbp" );
 $query = $this->EE->db->get( "currency" );

 $usd = '';
 $eur = '';
 $gbp = '';

 $usd_convert = $price * $usd;
 $eur_convert = $price * $eur;
 $gbp_convert = $price * $gbp;

 return $usd;
}

Link to comment
https://forums.phpfreaks.com/topic/273540-get-data-from-database-into-variable/
Share on other sites

  • 2 weeks later...

If you got a currency table, with columns usd, eur, gbp:

public function convert() {

 $price = $this->EE->TMPL->fetch_param('price');
 if( $price === FALSE ) {
	 return array();
 }

   $query = $this->EE->db->select( "usd, eur, gbp" )->get( "currency" );

   $currency_values = $query->num_rows() ? array_shift($query->result()) : false; // Only if there are results

   if (!$currency_values) {
      throw new Exception("No currency row found in the database");
   }

   foreach ($currencies as $currency => $currency_values) {
      if (!$currency_values) {
         throw new Exception("$currency currency has blank value");
      }
   }

   $return = array(   
          'usd' => $price * $currency_values['usd'],
          'eur' => $price * $currency_values['eur'],
          'gbp' => $price * $currency_values['gbp']
       );

 return $return;
}

 

I got no idea actually about "EE" but I made that based on the documentation hoping it'll help or give you idea at least.

 

Btw. having a currency table with only one row doesn't seem to make sense to me, I could have understood it wrong though, but if I didn't, I suggest having a currency row with ( currency varchar, usd_value decimal ) table instead

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.