hi frens,

i have a weird doubt haunting me. please clear it for me..

lets say i have a table(EMP) containing fields emp_name and emp_dept, n there are around 10 records in the table. now i want to print all the emp_name. i know we can do as follows

echo $empname;

and loop it.

is there any other way of getting all the names at one go as a array??


Edited by puvi: n/a

6 Years
Discussion Span
Last Post by puvi

A standard way to do it would be

while ($empname=mysql_fetch_array($result)){
   echo $empname['emp_name'];

or if you want it as an array you could always

$empArray = array();
while ($empname=mysql_fetch_array($result)){

You could always try PDO. This has a command for getting record fields -> array using fetchAll. From the php manual on PDO:

$sth = $dbh->prepare("SELECT name, colour FROM fruit");

/* Fetch all of the values of the first column */
$result = $sth->fetchAll(PDO::FETCH_COLUMN, 0);

Will give:

    [0] =>
    string(5) => apple
    [1] =>
    string(4) => pear
    [2] =>
    string(10) => watermelon

However, introducing PDO for this may be a bit heavy-handed. If you're looking for a simple solution, I suggest placing the values into an array via loop as mentioned by sudeepjd.


thanks guys..

please clear one more doubt..

lets say, i have a table(Name) with fields first_name, mid_name and last_name. records in the table are as follows:
1. tom-robert-hanks
2. angel-diva-hanks
3. nick-kick-hanks
4. jingle-doll-bond
5. james-cool-bond
6. john-mac-bond

now i want to fetch all the first_name having last_name as bond into a array.

$query="select * from Name where last_name='hanks'";

now, what will be there with $row, is it just the 1st row containing hanks??
how do i access the next two names..

pls clear this for me..it may sound silly but really confusing me..



Hmm... Did you read the previous post... Cos you missed out on the while loop. What the mysql_fetch_array() does is to get one row at a time and move the pointer on to the next row. So the second call to mysql_fetch_array() with the same $result resource would give you the information from the second row, hence the need for the while loop.

So in order to get all the names you would need

$name = array();
$query="select * from Name where last_name='hanks'";
while ($row=mysql_fetch_array($result)){
   $name[]=$row['first_name']." ".$row['mid_name']." ".$row['last_name'];

The var_dump would give you the array of $name and the keys used to access each of the names.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.