简体   繁体   English

SQL:获取具有相同ID的所有列记录

[英]SQL: get all column records with same id

I'm quite new to sql and I'm having trouble writing this 我是sql的新手,在编写此代码时遇到麻烦
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 ADEF i tried this in PHP: 我想要一个查询,该查询将返回给我我给它的ID的名称...说如果我要1,我希望它返回ADEF我在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? 但这仅给我找到ID为1的名字,我还缺少什么?

You should iterate the whole result set using while() and mysql_fetch_assoc(). 您应该使用while()和mysql_fetch_assoc()迭代整个结果集。 example: 例:

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

mysql_fetch_assoc returns one row from your result set so it will only return the first value. mysql_fetch_assoc从结果集中返回一行,因此它将仅返回第一个值。 You need to loop through your result set ($result3 in your code) and get all the rows. 您需要遍历结果集(代码中的$ result3)并获取所有行。

btw, the mysql_ family of functions is quite old and most people would suggest using the mysqli_ family, or even better, PDO 顺便说一句,mysql_函数家族已经很老了,大多数人会建议使用mysqli_家族,或者甚至更好的PDO

EDIT: A very basic PDO example: 编辑:一个非常基本的PDO示例:

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

You can use this code and verify you could able to retieve 您可以使用此代码并验证是否可以重新放置

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

Loop through your result set using mysql_fetch_array(). 使用mysql_fetch_array()遍历结果集。 For more help click here 如需更多帮助, 请点击这里

Try this 尝试这个

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM