tags:

views:

47

answers:

2

I have a table with attributes like this:

likes(id, message, ip, time)

id is the primary key and is auto-incrementing. Whet I want to do is select 30 rows from this table based on an id that I provide.

I can build a random array of all IDs I want to grab from the table, now I just need to go about doing that. My usual SQL query would be:

SELECT message
FROM `likes`
WHERE id=$id
LIMIT 1

But I need to select 30 rows. There are two ways I can do this, I can either use a FOR loop with 30 queries, or combine it all into one query and grab them all at the same time. Obviously I would like to do the latter.

Can anyone help me out on the SQL query to use to grab more than one row from my database table at once? And perhaps an example of how I would parse these into an array for easy retrieval?

Greatly appreciated, thanks.

+5  A: 

You could use the IN operator, so it would be something like this:

SELECT message FROM likes WHERE id IN (1, 2, 3, 4, 5, ...)
Carko
+1  A: 
$ids = array(1,2,3,4,5,6,7,8,9); //or however many
$query = "SELECT * FROM `likes` WHERE `id` IN (".implode(', ', $ids).")";
$res = mysql_query($query);
$results = array();
while($tmp = mysql_fetch_array($res)) {
     $results[$tmp['id'] = $tmp;
}

Will give you an array, $results, sorted by key ['id'], with each being an array on each answer key-- 'id', 'message', 'ip', 'time'. So for example:

for($results as $key => $val) {
    echo "${val['ip']} posted {$var['message']} on {$val['time']} <br/>";
}
zebediah49
In PHP you create an array with `$ids = array(1,2,3,...);`.
too much php
Thanks *facepalm*.
zebediah49