I have a PHP array generated by the following code:
$sql = "SELECT adresa.Id_Adresa as id FROM adresa";
$result = $this->os->db->conn->query($sql);
$data = array();
while ($r = $result->fetch(PDO::FETCH_ASSOC)) {
$data[] = $r;
}
I want to grab the very first id of this array. How can I do that without parsing all the items? Thanks in advance.
asked May 10, 2011 at 18:40
-
You should add an ORDER BY to your query because the order of data returned is not guarantee without it.Luc M– Luc M2011年05月10日 18:50:35 +00:00Commented May 10, 2011 at 18:50
-
@Luc M, I do not actually need to order the results. The query I actually use is more difficult and it returns only one id. Thanks.Giku Promitt– Giku Promitt2011年05月11日 05:12:50 +00:00Commented May 11, 2011 at 5:12
3 Answers 3
When you say first id of this array
I am assuming that is the $data
array, just do:
print_r($data[0]);
answered May 10, 2011 at 18:42
-
1well, assuming the array does look like [{'id':'1'}], I want to display '1'.Giku Promitt– Giku Promitt2011年05月11日 05:50:36 +00:00Commented May 11, 2011 at 5:50
-
well then you need to do
echo data[0]->id;
Naftali– Naftali2011年05月11日 13:51:48 +00:00Commented May 11, 2011 at 13:51
Why don't you limit the number of items returned if you don't need them?
$sql = "SELECT adresa.Id_Adresa as id FROM adresa LIMIT 1";
answered May 10, 2011 at 18:42
$sql = "SELECT adresa.Id_Adresa as id FROM adresa LIMIT 1";
$result = $this->os->db->conn->query($sql);
$firstId = $result->fetchColumn(0);
See the docs at https://www.php.net/manual/en/pdostatement.fetchcolumn.php
answered May 10, 2011 at 18:43
-
$result->fetchColumn() returned me just what I was needing.Thanks all & especially thanks nickf.Giku Promitt– Giku Promitt2011年05月11日 08:15:22 +00:00Commented May 11, 2011 at 8:15
-
@Giku Promitt - If this was the answer which solved your problem, you can click the green checkmark (✔) to the left here.nickf– nickf2011年05月11日 14:57:36 +00:00Commented May 11, 2011 at 14:57
lang-php