开发者

Print mysql results column by column

I feel incredibly stupid for not being able to figure this out, but I guess that's what Stackoverflow is for. If someone could point me to helpful resources or explain to me how to solve this, I would be very appreciative.

Basically I'm fetching a couple of rows from a table, and now I need to be able to print them out the value of each row's field, followed by the values of each row from a different field, and so on. It's hard to explain, but let me give you an example.

Let's say we have a table with three fields: id - name - url. Now I want to be able to output the result in this order:

1
2
3
John
Steven
Patrick
http://google.com/
http://stackoverflow.com/
http://php.net/

How do I loop through the results of m开发者_开发技巧y query in order to achieve this?


Well you should make an array and then spew it out:

$ids = array();
$names = array();
$urls = array();
while($row = ...){
    $ids[] = $row['id'];
    $names[] = $row['name'];
    $urls[] = $row['url'];    
}

foreach($ids as $id) {
    echo $id . PHP_EOL;
}
//do the same for  the other 2


You can do this via union. The only tricky part is making sure to cast all of the fields to a common data type (in this case, text). Also, each subquery is ordered by id to make sure that the ordering is consistent.

select id::text
from table
order by id
union
select name::text
from table
order by id
union
select url::text
from table
order by id


$result = mysql_query("SELECT id, name, url FROM yourtable") or die(mysql_error());
$data = array()
while($row = mysql_fetch_asssoc($result)) {
    $data[] = $row;
}
foreach(array('id', 'name', 'url') as $key) {
   foreach($data as $idx => $val) {
      echo $val[$key], "\n";
   }
}


The simplest way is

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $ids[] = $row['id'];
    $names[] = $row['names'];
    $wwws[] = $row['website'];
}

Then you iterate over the three arrays. There are surely better methods for doing this!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜