0

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
2
  • You should add an ORDER BY to your query because the order of data returned is not guarantee without it. Commented 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. Commented May 11, 2011 at 5:12

3 Answers 3

2

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
2
  • 1
    well, assuming the array does look like [{'id':'1'}], I want to display '1'. Commented May 11, 2011 at 5:50
  • well then you need to do echo data[0]->id; Commented May 11, 2011 at 13:51
1

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
0
0
$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
2
  • $result->fetchColumn() returned me just what I was needing.Thanks all & especially thanks nickf. Commented 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. Commented May 11, 2011 at 14:57

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.