Jump to content

[SOLVED] Small question regarding Database Results?


Solarpitch

Recommended Posts

Hi,

 

Can someone clear this up for me please? I'm trying to get the value of the query by "echo $row;" but this just prints out an Object ID#4 or something. Is it because row contains both the value and the reference to it ie. the Object ID?

 

How do I correctly access the value queried in $row?

 

<?php

$query = $this->client->query("SELECT SUM(price) FROM sales WHERE ticketnumber = ".$ticketnumber."");
$row = $query->row();

?>

Wouldn't know because you appear to be using some third party db abstraction layer. One would assume however that your query method is returning a result resource (same as mysql_query does) and needs to be passed to something like mysql_fetch_assoc in order to actually be usefull.

A clearer (maybe) example using php's standard mysql extension without any abstraction (and a clearer query).

 

$sql = "SELECT SUM(price) AS price FROM sales WHERE ticketnumber = $ticketnumber LIMIT 1";
if ($result = mysql_query($sql)) {
  if (mysql_num_rows($result)) {
    $row = mysql_fetch_assoc($result);
    echo $row['price'];
  }
}

I'm using the framework Codeigniter so thats why it appears as a third party db abstraction. Below is an example of a function I have that works perfect with the same idea.

 

<?php

function credit_sales()
{   
//Using Codeigniter this will produce select sum(price) as price_total from sales where type = 'credit'
$this->client->select_sum('price', 'price_total');
$query = $this->client->get_where('sales', array('type' => 'credit');


$row = $query->row();
return $row->price_total;

//THIS WILL OUTPUT THE CORRECT RESULT: 899.99 or whatever
}

?>

 

But when I apply the same context ($row->price_total;) to the query I'm trying to use, it doesnt seem to work. (Edit: When I say doesnt work, I mean it prints out "Object ID#4")

Im sure if you used the query I posted above you would get the same result.

 

The problem is you don't define the alias price_total anywhere in your query. I assume (never used Codeignitor) that thats what the second argument to select_sum does (defines an alias).

It does yeah. Not to worry, I'll play around with it here anyway. Your query works fine but ill try and get it to work using the Codeigniter way. It may be because I have a similar query in the same function and somewhere along the lines its getting messed up.

 

Thanks for your help.

I'm sure my query would also work fine with the code you posted in your original post. eg;

 

<?php

$query = $this->client->query("SELECT SUM(price) AS price FROM sales WHERE ticketnumber = $ticketnumber LIMIT 1");
$row = $query->row();
echo $row->price;

?>

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.