468,249 Members | 1,467 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,249 developers. It's quick & easy.

Problem iterating thru associative array created by using SQL query.


I am using PHP 5.1 and MySQL. I have a result set obtained by executing
PDO:: query. I want to create an XML file by using this result set. The
XML file will contain column names as XML node name and column values
as node values.

$orders = $db->query($sql);

if (!empty($orders)) {

foreach ($orders as $row) {

foreach($row as $key=>$value) {
print $key . " => " . $value . "<br>";
// XML Elements will be created here...

The result of this loop as follows:

orderID => 1
0 => 1
packageSKU => SKU1
1 => SKU1
fullName => John Doe
2 => John Doe
address =>address1
3 =>address1
city => city1
4 => city1
itemTypeLabel => mailer
5 => mailer

When I am iterating through foreach loop, I am getting associative
array names and indices together. For example, after getting orderID as
$key in the first run, I am getting 0 as $key in the second run, etc.
which I don't want to. I just want to use the associative array names.

I appreciate if you can let me know if you have any idea what might be
the reason.

Thanks in advance.


Pelin Bali.

Mar 8 '06 #1
3 2490

Try changing the line
$orders = $db->query($sql);
to :
$orders = $db->query($sql, PDO::FETCH_ASSOC);

I don't know why that option is not shown on the php.net docs for PDO,
but it does infact work for me (php 5.1.2)

More info can be found here:

Hope that helps,

Mar 8 '06 #2
Hash: SHA1

pbali wrote:
I appreciate if you can let me know if you have any idea what might be
the reason.



And check the documentation of your DB abstraction layer, to see if it's
possible to change between MYSQL_ASSOC, MYSQL_NUM and MYSQL_BOTH.

- --
- ----------------------------------
Iván Sánchez Ortega -i-punto-sanchez--arroba-mirame-punto-net

http://acm.asoc.fi.upm.es/~mr/ ; http://acm.asoc.fi.upm.es/~ivan/
Jabber:iv*********@jabber.org ; iv*********@kdetalk.net
Version: GnuPG v1.4.2 (GNU/Linux)

iD8DBQFED2EI3jcQ2mg3Pc8RAn9SAJ4kf0YGvBvxCViO2Cpsnj CBB6fYyACePyTF
Mar 8 '06 #3
Thanks Carl,

That worked. *:)


Mar 9 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

27 posts views Thread by Abdullah Kauchali | last post: by
2 posts views Thread by Zenobia | last post: by
6 posts views Thread by mark4asp | last post: by
34 posts views Thread by Christopher Benson-Manica | last post: by
14 posts views Thread by Yereth Jansen | last post: by
1 post views Thread by geoffcastro | last post: by
41 posts views Thread by Rene Nyffenegger | last post: by
3 posts views Thread by Robert Mark Bram | last post: by
reply views Thread by NPC403 | last post: by
reply views Thread by kermitthefrogpy | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.