views:

505

answers:

3

Is it possible to output SQL query result in one string or variable? (i'm bad in php and mysql) Let's say I have db "agents" with columns - agent_id, agent_fname, agent_lname, agent_dept.

Using this query:

$sql = SELECT a.`agent_fname` FROM agents a WHERE a.`agent_dept` = 'FCA'

I want to get a string or a variable, so I can use it in any place of my php file (i.e. $my_variable which outputs the result of my query). Is it possible? If yes - how?

Thank you!

*I have more than one row.

+3  A: 
$result = mysql_query($sql);

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    printf("Name: %s", $row['agent_fname'],);  
}
Dominic Rodger
+2  A: 

I'm assuming you are doing something like:

$result = mysqli_query ($link, $sql).

The 'i' in mysqli is for 'improved' which is what you should be using these days.

This $result is not your output yet. You must call:

while ($row = mysqli_fetch_assoc($result)) {
     print_r ($row);
}

The above code gives you $row, which is your actual output, in the form of an array.

Michael
A: 

If you want to pass around a single variable representing your records. You could build a two dimensional array. like:

$records = array();
$mysqli_result = mysqli_query ($link, $sql);

while ($row = mysqli_fetch_assoc($result)) {
     $records[] = $row;
}

This will give you an array variable, $records, will all of your results. Which is easy to pass around. (maybe as an arg to another function.) HOWEVER, this is a pattern that can eat up a lot of memory.

It is much better to pass around the $mysqli_result.

Lance Rushing