views:

73

answers:

3

Hi all,

If I'm getting my data from Mysql like so:

    $result = $dbConnector->Query("SELECT * FROM branches, businesses WHERE branches.BusinessId = businesses.Id ORDER BY businesses.Name");
    $resultNum = $dbConnector->GetNumRows($result);
    if($resultNum > 0)
    {
        for($i=0; $i < $resultNum; $i++)
        {
            $row = $dbConnector->FetchArray($result);
            // $row['businesses.Name'];
            // $row['branches.Name'];
            echo $row['Name'];
        }
    }

Does anyone know how to print the field Name in businesses and how to print the name from branches?

My only other alternative is to rename the fields or to call Mysql with two separate queries.

Thanks in advance

+2  A: 

Be more specific in your SQL:

$result = $dbConnector->Query("SELECT branches.Name as branch_name, businesses.Name as business_name FROM branches, businesses WHERE branches.BusinessId = businesses.Id ORDER BY businesses.Name")
$resultNum = $dbConnector->GetNumRows($result);
if($resultNum > 0)
{
    for($i=0; $i < $resultNum; $i++)
    {
        $row = $dbConnector->FetchArray($result);
        echo $row['branch_name'];
        echo $row['business_name'];
    }
}
Dominic Rodger
Thanks for the help, just what I needed!
ing0
+3  A: 

I would modify the SQL query, to rename fields in the select :

  • no need to rename the fields in the database
  • no need for two queries.

Something like this should work :

select branches.br_field1, branches.name as br_name, branches.br_field3,
  businesses.field1 ad bu_field2, businesses.name as bu_name
from
  ...

Of course, up to you choose the names ;-)


For more informations, don't hesitate to take a look at the manual :

A select_expr can be given an alias using AS alias_name. The alias is used as the expression's column name and can be used in GROUP BY, ORDER BY, or HAVING clauses.

(And there is more I didn't quote ^^ )

Pascal MARTIN
Thanks for the help, just what I needed!
ing0
@j.ingham06 : you're welcome ; have fun !
Pascal MARTIN
A: 

$result = $dbConnector->Query("SELECT businesses.Name buname, branches.Name braname FROM branches, businesses WHERE branches.BusinessId = businesses.Id ORDER BY businesses.Name"); $resultNum = $dbConnector->GetNumRows($result); [...] echo $row['buname']; echo $row['braname'];

You have to give alias names to the columns.

siposa