select json_build_object(
'id', users.id,
'name', users.name,
'items', jsonb_agg(inventory.name)
) json_result
from users
left join inventory on inventory.user_id = users.id
where users.id = 1
group by users.id, users.name
;
+============================================================================+
| json_result |
+============================================================================+
| {"id" : 1, "name" : "User 1", "items" : ["Stuff 1", "Stuff 2", "Stuff 3"]} |
+----------------------------------------------------------------------------+
CREATE TABLE images (
image_id INTEGER AUTO_INCREMENT PRIMARY KEY,
filename VARCHAR(255) NOT NULL UNIQUE
);
CREATE TABLE tags (
tag_id INTEGER AUTO_INCREMENT PRIMARY KEY,
tag VARCHAR(255) NOT NULL UNIQUE
);
CREATE TABLE images_tags (
image_id INTEGER NOT NULL,
tag_id INTEGER NOT NULL,
PRIMARY KEY (tag_id, image_id),
FOREIGN KEY (tag_id) REFERENCES tags(tag_id),
FOREIGN KEY (image_id) REFERENCES images(image_id)
);
select tbl1.*
from tbl tbl1
join tbl tbl2 on tbl1.num1 = tbl2.num2 and tbl1.num2 = tbl2.num1
where tbl2.id < tbl1.id
;
+====+======+======+
| id | num1 | num2 |
+====+======+======+
| 6 | 30 | 10 |
+----+------+------+
<?php
class StaticClass {
static $FILE_NAME = 'SOME_STATIC_FILE';
public static function getName()
{
return self::$FILE_NAME;
}
}
echo StaticClass::getName();
echo PHP_EOL . '====================' . PHP_EOL;
class InstansedClass {
private $FILE_NAME = 'SOME_INSTANCE_FILE';
public function getName()
{
return $this->FILE_NAME;
}
}
$instanseOfInstansedClass = new InstansedClass();
echo $instanseOfInstansedClass->getName();
$words = preg_split('/\W/', "Hello World");
function translate($word) {
$array = array(
'almaz' => "good",
'echo' => "php",
'html' => "css",
'sis' => "ki",
'hello' => 'привет',
);
$word = strtolower($word);
if (array_key_exists($word, $array)) {
echo $array[$word];
} else {
echo "Ключа $word не найдено.";
}
echo PHP_EOL;
}
foreach($words as $word) {
translate($word);
}
SELECT title, type
FROM (
SELECT
title,
type,
row_number() over (partition by type order by id) rnum
FROM test) numered
WHERE numered.rnum < 3
;
<?php
function split4bites ($input) {
$result = [];
$start = 0;
while ($start < strlen($input)) {
array_push($result, substr($input, $start, 4));
$start = $start + 4;
}
return $result;
}
$result = split4bites('jtoir75nsdt56odj');
print_r($result);
ADD COLUMN IF NOT EXISTSреализован только в MariaDB, но не существует в MySQL 5-8.
SELECT VERSION();
create table records (
`id` int not null auto_increment,
`text` text,
primary key(`id`)
);
<?php
//Получить значение текстового поля из запроса
$text = $_GET['text'];
//Подключиться к БД MySQL
$servername = "localhost";
$username = "username";
$password = "password";
try {
$pdo = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
throw new \PDOException($e->getMessage());
}
//Вставить данные в таблицу БД
$query = "insert into records (text) values (?);";
$stmt = $pdo->prepare($query);
$stmt->execute([$text]);
//Проверить вставленные данные
$query = "select * from records;";
$stmt = $pdo->prepare($query);
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
print_r($data);
<?php
$arr = array("hello" => "world", "how" => "are", "you" => "dude");
$result = array_reduce(
array_keys($arr),
function($acc, $key) use ($arr) {
return $acc . $key . '=' . $arr[$key];
},
''
);
echo $result;
SELECT `title` AS 'Заголовок статьи', `article`.`id` AS 'Id статьи'
FROM `article`
LEFT JOIN `photo` ON `photo`.`article_id` = `article`.`id` AND `photo`.`made` = 'before' -- or 'after'
WHERE `article_id` IS NULL
GROUP BY `article`.`id`
SELECT `title` AS 'Заголовок статьи', `article`.`id` AS 'Id статьи'
FROM `article`
WHERE NOT EXISTS (
SELECT `article_id`
FROM `photo`
WHERE `photo`.`article_id` = `article`.`id` AND `photo`.`made` = 'before' -- or 'after'
);
['products'] = [должен быть
'products' => [
con.query(`UPDATE promocode SET activated = activated + 1 WHERE promo = ${promo}`)
$txt = "Doctor";
$str_replsace = str_replace(" ", "+", $txt);
$content = file_get_contents("https://www.bbc.co.uk/search?q=$str_replsace");
preg_match_all('/<a [^>]+><span aria-hidden="false">([^<]+)<\/span><\/a>/im', $content, $matches);
$titles= array_unique($matches[1]);
//var_dump($titles);
foreach ($titles as $title) {
echo $title . PHP_EOL;
}
SELECT *
FROM devices
WHERE breaking > DATE_SUB(CURDATE(), INTERVAL 3 MONTH)
;
select
users.id,
users.name,
sum(money.value) as user_value
from users
join money on users.id = money.user_id
where value > 0
group by users.id, users.name
order by user_value desc;