开发者

Retrieve part of a MySQL column with PHP

开发者 https://www.devze.com 2022-12-31 16:57 出处:网络
For instance, if I have the following table: +----+---+----------+ id | a | position | +----+---+----------+

For instance, if I have the following table:

+----+---+----------+
| id | a | position |
+----+---+----------+
| 0  | 0 | 0        |
| 1  | 0 | 1        |
| 2  | 1 | 4        |
| 3  | 1 | 9        |
| 4  | 1 | 6        |
| 5  | 1 | 1        |
+----+---+----------+

and I want to get an array that contains the first 100 values from position where a is 1 in ascending order, what would I do?

Im guessing something like this:

$col = mysql_fetch_array( mysql_query('
SELECT `position`
FROM `table`
WHERE `a`="1"
ORDER BY `position` ASC
LIMIT 100
'));

I'd expect to get the f开发者_高级运维ollowing array:

+-------+-------+
| index | value |
+-------+-------+
| 0     | 1     |
| 1     | 4     |
| 2     | 6     |
| 3     | 9     |
+-------+-------+

but it doesn't work.

¿What should I do to make it work?

Thanks


mysql_fetch_array() gets a single row at a time from the result of your query. To access all of the rows you need a loop. Something like...

while ($row = mysql_fetch_array($result, MYSQL_NUM)) 
{
  printf("index: %s  value: %s", $row[0], $row[1]);  
}

I would take a closer look at: http://php.net/manual/en/function.mysql-fetch-array.php


Okay, couple of things:

Running the mysql_query inside the fetch_array is weird. Mysql_fetch_array works on a query result to put the individual lines of the result(as fetched) into an array. So when you're running it as you've got it, if it runs at all, it's only going to give you the first row, not the first hundred rows.

Second, the quoting looks pretty weird. Depending on the data type in "a", the double quotes might cause. (Haven't used MySQL in a bit, could be wrong.)

If I was going to do it, I'd do it like this:

$result = mysql_query("SELECT index, position FROM table WHERE a = 1 ORDER BY position ASC LIMIT 100");

while($col = mysql_fetch_array($result)){
    *do something*
}

*Thanks to JYelton for the Query reformat.


Your query is okay.

The problem is that mysql_fetch_array retrieves only one row. You should loop all the rows and add each value to your $col array.

$result = mysql_query('...');

while($row = mysql_fetch_array($result, MYSQL_NUM))
{
    $col[] = $row[0];
}

Now $col contains following:

Array
(
    [0] => "1"
    [1] => "4"
    [2] => "6"
    [3] => "9"
)
0

精彩评论

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