krasatos
krasatos

Reputation: 1177

SQL: get all column records with same id

I'm quite new to sql and I'm having trouble writing this
i have a table like this

id   name
1   A
2   B
3   C
1   D
1   E
1   F
...

I want a query that will return to me the names of the ID i give it... say if i ask for 1, i want it to return A D E F i tried this in PHP:

$result3 = mysql_query("SELECT name FROM table WHERE id='1'", $link);

    $pfilearray=array();
    $pfilearray=mysql_fetch_assoc($result3);

    print_r($pfilearray);

but this gives me only the first name found with id 1, what am i missing?

Upvotes: 0

Views: 2362

Answers (5)

liquorvicar
liquorvicar

Reputation: 6106

mysql_fetch_assoc returns one row from your result set so it will only return the first value. You need to loop through your result set ($result3 in your code) and get all the rows.

btw, the mysql_ family of functions is quite old and most people would suggest using the mysqli_ family, or even better, PDO

EDIT: A very basic PDO example:

$ddh = new PDO( /* connection details */ );
$sth = $dbh->prepare('SELECT name FROM table WHERE id= ? ');
$sth->execute(array(1));
$names = $sth->fetchAll();

Upvotes: 1

heyanshukla
heyanshukla

Reputation: 669

Loop through your result set using mysql_fetch_array(). For more help click here

Upvotes: 1

Akhil Thayyil
Akhil Thayyil

Reputation: 9403

Try this

$result3 = mysql_query("SELECT name FROM table WHERE id='1'", $link);
while($row=mysql_fetch_array($result3))
{
  echo $row['name'];
}

Upvotes: 0

Vikram
Vikram

Reputation: 7515

You can use this code and verify you could able to retieve

while($row = mysql_fetch_array($result3))
{
  echo $row['name'];
  echo "<br>";
}

Upvotes: 1

dhchen
dhchen

Reputation: 1198

You should iterate the whole result set using while() and mysql_fetch_assoc(). example:

while(($rs=mysql_fetch_assoc($result3))!=null)
{
    $pfilearray[]=$rs['name'];
}
print_r($pfilearray);

Upvotes: 4

Related Questions