First, let me apoligize. This is a rather long-winded question. But, I think maybe I'm missing something here? I've just starting using PDO for all my database queries. I'm using fetchall which returns multidimensional arrays. This seems to complicate things a bit when making use of the results. I looked at both fetch and fetchall and it seems like I want to be using fetchall. Correct me if I'm wrong.
public function getData($sql,$params) {
// run a select query
try {
$this->stmt = $this->conn->prepare($sql);
$this->stmt->execute($params);
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
catch(PDOException $e) {
throw new Exception('DATABASE ERROR: ' . $e->getMessage());
}
}
So, lets say I want to generate a list of locations. The old way would be to run a query and extract the results with a while loop. They would extract as the column name from the database. Pretty simple.
PDO seems a bit more complicated. The query returns as a multidimensional array like so.
Array
(
[0] => Array
(
[location_id] => 1
[location_city] => City 1
[state_name] => State 1
)
[1] => Array
(
[location_id] => 2
[location_city] => City 1
[state_name] => State 1
)
[2] => Array
(
[location_id] => 3
[location_city] => City 1
[state_name] => State 1
)
[3] => Array
(
[location_id] => 6
[location_city] => City 1
[state_name] => State 2
)
and so on...
I then have to run a foreach loop to straighten things out.
foreach ($locations as $shops) {
$arr[$shops['state_name']][$shops['location_id']] = $shops['location_title'];
}
which turns the previous array into:
Array
(
[State 1] => Array
(
[1] => City 1
[2] => City 2
[3] => City 3
)
[State 2] => Array
(
[1] => City 4
[2] => City 5
)
)
Once I get it here, it's more foreach loops to pick the data apart even further. This seems to start making code fatten out quite a bit.
I previously used dropdown functions to generate lists. I would pass an associative array to the function, it would do it's thing and create the dropdown. With PDO and fetchall, I'm having to adjust the array either inside the dropdown function or before it gets there.
I guess I really just want to know if I'm going about this right or if I'm missing something what is it (besides a deeper understanding of PHP, that's a given ).