description |
---|
We only serve models here 💁♂️💁♀️ |
FMVC provides an abstracted connection to SQL Databases. This abstraction is called: FMVC/Data/SqlDataBase
. This abstraction enables automatic configuration from a pool of previously defined connections. Those connections can be specified in config/db.json
:
{
"default": {
"protocol": "mysql",
"host": "localhost",
"username": "root",
"password": "root",
"port": "3306",
"databse": "my_db"
}
}
Internally, FMVC used PDO to provide a generic approach to connecting to all kinds of databases. To generate the corresponding connection string, the framework loads the components from the configuration specified by the string passed to it's constructor:
use FMVC\Data\SqlDataBase;
$conn = new SqlDataBase("default");
Depending on the type of the database (especially SQLite3) the format of the connection string differs. Here are the two supported formats:
- Normal SQL-databases:
{
"default": {
"protocol": "mysql|pgsql|mssql",
"host": "localhost",
"username": "root",
"password": "root",
"port": "3306",
"databse": "my_db"
}
}
- SQLite:
{
"default": {
"protocol": "sqlite",
"host": "file.db",
"username": "",
"password": "",
"port": "",
"database": ""
}
}
Now that we have the credentials, we are ready to connect to our database. Luckily, our database class does that for us.
A connection is cool, yeah, but what a database really does for us is providing access to persistent data. FMVC/Data/SqlDataBase
also has some for that in it's pocket:
exec(string $query): int
provides a point to execute ddl statements like insert, update or delete statements. This method will only pass on the status returned from the query.
use FMVC\Data\SqlDataBase;
$base = new SqlDataBase("local");
echo $base->execute(
"Insert into users(nr, name, stuff) values(1, 'name', 'stuff')"
);
This query would return 1 as 1 dataset was affected.
query(string $query): array
is the interface point for all your DataQueryLanguage stuff. Does not matter if you want one or - maybe you already guessed it - a bazillion datasets. Just pass your query to this baby and it will fulfill your wildest data dreams ...or return an empty array, if you fucked it up.
use FMVC\Data\SqlDataBase;
$base = new SqlDataBase("local");
print_r( $base->query(
"SELECT * from users"
));
In this case print_r would output all datasets found in the users table.
We hope you got some insight into how FMVC works with databases. Have fun!