<?php
error_reporting(E_ALL); // репорт ошибок в файл error_log
ini_set('display_errors', 'On'); // вывод сообщения об ошибке
var_dump($_POST);
var_dump($pdo->errorInfo());
UPDATE TableA LEFT JOIN (
SELECT MIN(Id) AS id, Name FROM TableB GROUP BY Name
) AS b
ON TableA.Name = b.Name
SET TableA.TableBId = b.id
select
users.id, users.name, group_concat(country.country) as visited
from
users
left join user_to_country on user_to_country.user_id = users.id
left join country on user_to_country.country_id = country.id
where u_status = 1
group by users.id, users.name;
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect($host, $user, $pass, $db_name);
$link->set_charset("utf8mb4");
$sql = "INSERT INTO `events` (`title`, `discription`, `date`, `img`) VALUES (?,?,?,?)";
$stmt = $link->prepare($sql);
$stmt->bind_param("sssss", $title, $discription, $date, $path);
$stmt->execute();
$host = '127.0.0.1';
$db = 'test';
$user = 'root';
$pass = '';
$port = "3306";
$charset = 'utf8mb4';
$options = [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\PDO::ATTR_EMULATE_PREPARES => false,
];
$dsn = "mysql:host=$host;dbname=$db;charset=$charset;port=$port";
$pdo = new \PDO($dsn, $user, $pass, $options);
$sql = "INSERT INTO `events` (`title`, `discription`, `date`, `img`) VALUES (?,?,?,?)";
$stmt = $link->prepare($sql);
$stmt->execute([$title, $discription, $date, $path]);
public function addProduct(){
$query = 'INSERT INTO products (title, price, description, category, image, active) VALUES (?,?,?,?,?,?)';
$stmt = $this->db->prepare($query);
$stmt->bind_param("ssssss", $this->title, $this->price, $this->description, $this->category, $this->image, $this->$active);
$stmt->execute();
}
document.querySelector('.case-print')
Просто актуальной инфы так мало по этому, а я вылез из 2015 года.
exit('Ошибка подключения к базе данных!');
дважды глупость. Пользователю сайта не интересно читать, что у тебя сломалось - база данных или деньги на пиво кончились. Как программисту, тебе эта бессмысленная фраза тем более бесполезна, она ничего не говорит о том, ЧТО КОНКРЕТНО сломалось, чтобы ты мог исправитьif ($numRows > 0) {
бессмысленный кусок кодаwhile ($row = $result->fetch_assoc()) {
заменяется на $result->fetch_all(MYSQLI_ASSOC)
$this->connect()
коннектимся каждый раз, чтобы выполнить запрос, серьёзно?class Handler extends Dbh
ВООБЩЕ непонятно зачемclass Dbh
{
public $conn;
public function __construct($config)
{
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$this->conn = new mysqli(...$config);
$this->conn->set_charset('utf8mb4');
}
public function preparedQuery($sql, $params, $types = '')
{
$types = $types ?: str_repeat('s', count($params));
$stmt = $this->conn->prepare($sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
return $stmt;
}
public function selectResult($sql, $params, $types = '')
{
if (!$params) {
return $this->conn->query($sql);
}
return $this->preparedQuery($sql, $params, $types)->get_result();
}
public function selectAll($sql, $params = [], $types = '')
{
return $this->selectResult($sql, $params, $types)->fetch_all(MYSQLI_ASSOC);
}
public function selectAssoc($sql, $params = [], $types = '')
{
return $this->selectResult($sql, $params, $types)->fetch_assoc();
}
public function selectRow($sql, $params = [], $types = '')
{
return $this->selectResult($sql, $params, $types)->fetch_row();
}
public function selectCell($sql, $params = [], $types = '')
{
$row = $this->selectRow($sql, $params, $types);
return $row ? $row[0] : false;
}
}
position.php
class Position
{
protected $dbh;
public function __construct(Dbh $dbh)
{
$this->dbh = $dbh;
}
// Получаем все позциии из БД и возвращаем их в массиве $output если записей больше нуля
public function getAllPositions()
{
return $this->dbh->selectAll('SELECT * FROM positions');
}
protected function addPosition($content)
{
$count = $this->dbh->selectCell('SELECT count(*) FROM positions');
if ($count < 10) {
$this->dbh->preparedQuery("INSERT INTO positions (content) VALUES (?)", [$content]);
}
}
protected function deletePosition($id)
{
$this->dbh->preparedQuery("DELETE FROM positions WHERE id = ?", [$id]);
}
//Поиск позиций в БД по столбцу content
protected function searchPosition($content)
{
$content = "%$content%";
return $this->dbh->selectAll('SELECT * FROM positions WHERE content LIKE ?',[$content]);
}
}
return [
'db' => [
'host' => '127.0.0.1',
'username' => '',
'password' => '',
'dbname' => '',
'port' => 3306,
],
];
$config = require 'config.php';
$dbh = new Dbh($config['db']);
$position = new Position($dbh);
switch ($_GET['action']) {
case 'getpositions':
$output = $position->getAllPositions();
echo json_encode($output);
break;
case 'addposition':
$content = $_GET['content'];
$position->addPosition($content);
break;
case 'getsearchpositions':
$content = $_GET['content'];
$output = $position->searchPosition($content);
echo json_encode($output);
break;
case 'deleteposition':
$id = $_GET['id'];
$position->deletePosition($id);
break;
default:
header("HTTP/1.0 400 Bad Request");
}
UPDATE first_table
JOIN second_table ON first_table.id = second_table.id
SET first_table.count = first_table.count + second_table.total_count, second_table.total_count = 0
WHERE second_table.id = 1;
SELECT user_id
FROM some_table
WHERE num IN (878, 925, 242)
GROUP BY user_id
HAVING COUNT(DISTINCT num) = 3 -- 3 количество вариантов
;
SELECT some_table.user_id
FROM some_table
JOIN some_table st1 ON st1.user_id = some_table.user_id AND st1.num = 925
JOIN some_table st2 ON st2.user_id = some_table.user_id AND st2.num = 242
WHERE some_table.num = 878
;
SELECT user_id, GROUP_CONCAT(DISTINCT num ORDER BY num)
FROM some_table
WHERE num IN (878,925,242)
GROUP BY user_id
HAVING GROUP_CONCAT(DISTINCT num) = '242,878,925'
;