2

I'm working on a app that requires a DB and I'm getting some problems, the code seems good but its only printing 1 row when I have 2, I have tested when I have it with 5 and I still get 1.

What I'm wanting to do is make an array of all the item_id's; I know I'm getting all fields at the moment but that was just for testing.

index.php:

<?php

mysql_connect('localhost', 'aaran', '*********');
mysql_select_db('aaran_aff_io');

$query = mysql_query("SELECT * FROM `items` WHERE `owner`='aaranmcguire'");
$results = mysql_fetch_array($query);

echo '<pre>';
print_r($results);

?>

DB:

SQL DB

DB Structure:

CREATE TABLE `items` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `item_id` int(11) NOT NULL,
  `name` varchar(55) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `thumbnail` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `url` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `owner` varchar(55) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
2
  • 2
    Amazing how many people can read an answer written here on SO, but can't read the manual Commented Jan 10, 2012 at 21:02
  • @MarkBaker i did, i was trying the print_r at first so it was skipping results, my bad i guess.. Commented Jan 10, 2012 at 21:10

3 Answers 3

11

mysql_fetch_array only returns one row at a time. If you want all the rows placed into an array, you can iterate over the result set:

$query = mysql_query("SELECT * FROM `items` WHERE `owner`='aaranmcguire'");
$rows = array();
while ($row = mysql_fetch_array($query)) {
    $rows[] = $row;
}

echo '<pre>';
print_r($rows);
Sign up to request clarification or add additional context in comments.

1 Comment

thanks!... i was going something like this before but i was having problems because i was doing a separate print_r... link i will accept it as a answer when it allows me.
1

Have a look at the manual for mysql_fetch_array. It returns the next row when it's called.

while ($row = mysql_fetch_array($result)) {
    print_r($row);
}

Comments

0

mysql_fetch_array() only returns one row at a time so you must use a while loop to iterate over all the rows.

while($row = mysql_fetch_array($query)) {
    echo '<pre>';
    print_r($row);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.