Answer the question
In order to leave comments, you need to log in
Whether correctly implemented connection to a DB?
Good afternoon, I'm making a test site in php using mvc, according to this topic. But it does not implement a connection to the database.
How I implemented it:
In core/model.php, I created a db method containing a database connection.
class Model
{
static function db()
{
define('HOST', 'localhost');
define('USER', 'blog');
define('PASS', '12345');
define('DB', 'blog');
$db = new mysqli(HOST, USER, PASS, DB);
if ($db->connect_errno) {
echo "Не удалось подключиться к MySQL: {$db->connect_error}";
}
return $db;
}
public function get_data()
{}
}
class Model_Portfolio extends Model
{
public function get_data()
{
$link = self::db();
$query = "SELECT * FROM blog ORDER BY id DESC";
$result = $link->query($query);
while ($row = $result->fetch_assoc()) {
$articles[] = $row;
}
$link->close();
return $articles;
}
}
class Controller_Portfolio extends Controller
{
function __construct()
{
$this->model = new Model_Portfolio;
$this->view = new View;
}
function action_index()
{
$data = $this->model->get_data();
$this->view->generate('portfolio_view.php', 'template_view.php', $data);
}
}
Answer the question
In order to leave comments, you need to log in
echo "Unable to connect to MySQL: {$db->connect_error}";
I would recommend not to store data for connecting to the database in constants. I would write it like this:
class Model
{
private static $db_creds = [
'user' => 'blog',
'host' => 'localhost',
'pass' => '12345',
'db' => 'blog'
];
static function db()
{
// закешируем соединение, зачем каждый вызов создавать новое?
static $db;
if (is_null($db)) {
$db = new mysqli(
self::$db_creds['host'],
self::$db_creds['user'],
self::$db_creds['pass'],
self::$db_creds['db']
);
if ($db->connect_errno) {
echo "Не удалось подключиться к MySQL: {$db->connect_error}";
// в следующий вызов попробуем еще раз
$db = null;
}
}
return $db;
}
public function get_data()
{}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question