if ($_FILES['profileImage']['error']) {
$errors = array(
1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
3 => 'The uploaded file was only partially uploaded',
4 => 'No file was uploaded',
6 => 'Missing a temporary folder',
7 => 'Failed to write file to disk.',
8 => 'A PHP extension stopped the file upload.',
);
throw new \ErrorException($errors[$_FILES['profileImage']['error']]);
}
class Db {
public $db;
public function __construct() {
$config = require __DIR__.'/config.php';
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false,
];
$dsn = 'mysql:host='.$config['host'].';charset=utf8;dbname='.$config['name'];
$this->db = new PDO($dsn, $config['user'], $config['password'], $options);
}
public function query($sql, $params = []) {
$stmt = $this->db->prepare($sql);
$stmt->execute($params);
return $stmt;
}
public function cell($sql, $params = []) {
return $this->query($sql, $params)->fetchColumn();
}
public function row($sql, $params = [], $mode=PDO::FETCH_ASSOC) {
return $this->query($sql, $params)->fetch($mode);
}
public function all($sql, $params = [], $mode=PDO::FETCH_ASSOC) {
return $this->query($sql, $params)->fetchAll($mode);
}
public function column($sql, $params = []) {
return $this->query($sql, $params)->fetchAll(PDO::FETCH_COLUMN);
}
public function lastInsertId() {
return $this->db->lastInsertId();
}
}
include 'Db.php';
$db = new Db;
addUser($db, 123, 111111111);
function addUser($db, $user_id, $date) {
$params = [
'user_id' => $user_id,
'date' => $date,
];
$db->query('INSERT INTO users (user_id, date) VALUES (:name, :date)', $params);
return $db->lastInsertId();
}
Будет ли нормально сделать вот так?
Как реализовать доступ к бд в классе пользователя?
public static function setup($pdo)
{
self::$db = $pdo;
}
session_start(); в начале документа index.php есть
Тогда не понятно, для чего нужен singleton, если класс уже уникальный используя только static методы
Правильно ли считать static методы глобальными вместе с их классами?
<?php
$login = $_POST['login'];
$email = $_POST['email'];
$password = $_POST['pass'];
$conn = new PDO('mysql:host=localhost; dbname=testbd', 'root', '', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$sql = "INSERT INTO users (login, email, password) VALUES (?,?,?)";
$stmt= $pdo->prepare($sql);
$stmt->execute([$login, $email, $password]);
$conditions = [];
$parameters = [];
// conditional statements
if (!empty($_GET['name']))
{
// here we are using LIKE with wildcard search
// use it ONLY if really need it
$conditions[] = 'name LIKE ?';
$parameters[] = '%'.$_GET['name']."%";
}
if (!empty($_GET['age']))
{
// here we are using equality
$conditions[] = 'age = ?';
$parameters[] = $_GET['age'];
}
$sql = "SELECT * FROM users";
// a smart code to add all conditions, if any
if ($conditions)
{
$sql .= " WHERE ".implode(" AND ", $conditions);
}
// the usual prepare/bind/execute/fetch routine
$stmt = $mysqli->prepare($sql);
$stmt->bind_param(str_repeat("s", count($parameters)), ...$parameters);
$stmt->execute();
$b = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
if($b) {
print_r($b);
} else {
echo "0 results";
}