Get rows from DB table

Permalink
Hi,

I want to connect to the database, get the rows and echo data from a table in the DB.

A lot of the code I am seeing in packages is deprecated according to this:
https://documentation.concrete5.org/developers/database-management/a...

So I am trying to use the new connection method etc.

Here's what I have so far, but it doesn't work (500 error):
$db = \Database::connection();
$id = 1;
$rows = $db->fetchAssoc('select * from btMyTable where id = ?', [$id]);
foreach($rows as $row) {
    echo "bID: " . $row["bID"]. " - First Name: " . $row["FirstName"]. " - Last Name" . $row["LastName"]. "<br>";
}


Not quite sure what the ID is for? So I have just assigned it 1 for now, maybe that is the issue.
Just can't find an example of this.

Thanks
Dave

madesimplemedia
 
Parasek replied on at Permalink Best Answer Reply
Parasek
fetchAssoc() returns the first row of the result as an associative array, so there is no need for a foreach loop.
In you example it will be:

$db = \Database::connection();
$id = 1;
$row = $db->fetchAssoc('select * from btMyTable where id = ?', [$id]);
echo "bID: " . $row["bID"]. " - First Name: " . $row["FirstName"]. " - Last Name" . $row["LastName"]. "<br>";

unless you want to get more than 1 row. Then you need to replace fetchAssoc() with fetchAll(). But then you will propably won't need that id.

$id in [$id] is just binded variable. It will replace question mark in sql query.
madesimplemedia replied on at Permalink Reply
madesimplemedia
Thanks for that, that's really useful to know.