我正在尝试学习,而不是认真构建任何东西,并试图学习最有效的构建方法。
这是从数据库中获取多个数据,为数据库中的每个字段创建一个新函数的最有效方法吗?
api.php
<?php
class MyAPI
{
private $mysqli;
protected $db;
public function __construct($db)
{
$this->db = $db;
}
public function getName($id)
{
$statement = $this->db->prepare("SELECT name FROM users where id = ?");
$statement->bind_param('i', $id);
$statement->execute();
$statement->bind_result($name);
$statement->fetch();
$statement->close();
return $name;
}
public function getMail($id)
{
$statement = $this->db->prepare("SELECT mail FROM users where id = ?");
$statement->bind_param('i', $id);
$statement->execute();
$statement->bind_result($mail);
$statement->fetch();
$statement->close();
return $mail;
}
}
show.php
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
require_once 'dbconnection.php';
require_once 'class/api.php';
$api = new MyAPI($db);
$id=1;
echo $api->getName($id);
echo $api->getMail($id);