Як в MySQL видалити дані з таблиці SQL запитом

У MySQL можна повністю очистити таблицю за допомогою двох основних команд:

1. DELETE (повільний, зберігає структуру та AUTO_INCREMENT)

DELETE FROM table_name;

Видаляє всі рядки, але зберігає структуру таблиці.Якщо в таблиці є AUTO_INCREMENT, лічильник не скидається.Для прискорення можна використати DELETE FROM table_name WHERE 1=1;

2. TRUNCATE TABLE (швидкий, скидає AUTO_INCREMENT)

TRUNCATE TABLE table_name;

Швидший за DELETE, бо не записує операції для кожного рядка в лог транзакцій.Скидає AUTO_INCREMENT до 1.Не можна використовувати з таблицями, що мають зовнішні ключі (FOREIGN KEY), якщо FOREIGN_KEY_CHECKS=1.

Який варіант вибрати?

  • Якщо потрібно просто очистити дані та зберегти AUTO_INCREMENT – DELETE.
  • Якщо потрібна швидкість і можна скинути AUTO_INCREMENT – TRUNCATE.

Якщо ж потрібно видалити саму таблицю разом із її структурою:

DROP TABLE table_name;

Ця команда повністю видалить таблицю, тому потім доведеться створювати її заново.

Якщо таблиця має зовнішні ключі, перед TRUNCATE чи DELETE потрібно вимкнути перевірку:

SET FOREIGN_KEY_CHECKS=0;
TRUNCATE TABLE table_name;
SET FOREIGN_KEY_CHECKS=1;

Ось кілька прикладів PHP-коду, що виконують очищення таблиці в MySQL за допомогою DELETE, TRUNCATE і DROP TABLE.

1. Використання DELETE

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test_db";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Помилка підключення: " . $conn->connect_error);
}

$sql = "DELETE FROM table_name";  // Видаляє всі дані, але зберігає структуру
if ($conn->query($sql) === TRUE) {
    echo "Дані успішно видалені!";
} else {
    echo "Помилка: " . $conn->error;
}

$conn->close();
?>

2. Використання TRUNCATE TABLE (швидше, скидає AUTO_INCREMENT)

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test_db";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Помилка підключення: " . $conn->connect_error);
}

$sql = "TRUNCATE TABLE table_name";  // Швидко очищає таблицю
if ($conn->query($sql) === TRUE) {
    echo "Таблиця очищена!";
} else {
    echo "Помилка: " . $conn->error;
}

$conn->close();
?>

3. Використання DROP TABLE (видаляє таблицю повністю)

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test_db";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Помилка підключення: " . $conn->connect_error);
}

$sql = "DROP TABLE table_name";  // Видаляє таблицю повністю
if ($conn->query($sql) === TRUE) {
    echo "Таблиця видалена!";
} else {
    echo "Помилка: " . $conn->error;
}

$conn->close();
?>

Який варіант вибрати?

  • DELETE – якщо потрібно очистити всі записи, зберігаючи AUTO_INCREMENT.
  • TRUNCATE TABLE – якщо потрібно швидко очистити таблицю і скинути AUTO_INCREMENT.
  • DROP TABLE – якщо потрібно повністю видалити таблицю.

💡 Якщо таблиця має FOREIGN KEY, перед TRUNCATE або DELETE додайте:

$conn->query("SET FOREIGN_KEY_CHECKS=0");
$conn->query("TRUNCATE TABLE table_name");
$conn->query("SET FOREIGN_KEY_CHECKS=1");

Робота з посиланнями другого рівня через .htaccess

Щоб .htaccess обробляв посилання другого рівня вкладення (наприклад, /url1/url2) і перенаправляв їх на url1/url2.php або на 404.php, потрібно внести наступні зміни в код, наведений в статті “Робота з Url у файлі .htaccess

Оновлений .htaccess файл:

RewriteEngine On

# Якщо файл або директорія існують, пропускаємо запит
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

# Перевіряємо, чи є запит виду /url1/url2
RewriteCond %{REQUEST_URI} ^/([^/]+/[^/]+)$
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.*)$ /$1.php [L]

# Перевіряємо, чи є запит виду /url
RewriteCond %{REQUEST_URI} ^/([^/]+)$
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.*)$ /$1.php [L]

# Якщо файл не існує, перенаправляємо на 404.php
RewriteCond %{REQUEST_URI} ^/([^/]+(/[^/]+)?)$
RewriteCond %{DOCUMENT_ROOT}/%1.php !-f
RewriteRule ^(.*)$ /404.php [L]

Як це працює:

Обробка вкладених URL (/url1/url2):

Умова RewriteCond %{REQUEST_URI} ^/([^/]+/[^/]+)$ перевіряє, чи є URL двох рівнів.
Умова RewriteCond %{DOCUMENT_ROOT}/$1.php -f перевіряє, чи існує файл url1/url2.php.

Обробка однорівневих URL (/url):

Умова RewriteCond %{REQUEST_URI} ^/([^/]+)$ перевіряє, чи є URL одного рівня.
Умова RewriteCond %{DOCUMENT_ROOT}/$1.php -f перевіряє, чи існує файл url.php.

Обробка 404:

Якщо жоден з файлів не знайдено, перенаправляємо запит на 404.php.

Додаткові поради:

Якщо потрібна обробка більшої глибини вкладення (наприклад, /url1/url2/url3), можна використовувати регулярний вираз із зірочкою:
RewriteCond %{REQUEST_URI} ^/([^/]+(/[^/]+)*)$

Для налагодження правил можна тимчасово увімкнути відображення запитів:

RewriteLogLevel 3

Перевірте, чи працюють запити на двох рівнях, і чи коректно обробляються запити, які не знаходять відповідних файлів.

Робота з Url у файлі .htaccess

Напишемо скріпт в файлі .htaccess який буде переадресовувати запити /url на відповідний PHP файл url.php, а якщо файл url.php не існує, то переадресовувати на файл 404.php

RewriteEngine On

# Перевіряємо, чи запит йде до URL виду /url
RewriteCond %{REQUEST_URI} ^/([^/]+)$
RewriteCond %{DOCUMENT_ROOT}/%1.php -f
RewriteRule ^(.*)$ /$1.php [L]

# Якщо файл не існує, переадресовуємо на 404.php
RewriteCond %{REQUEST_URI} ^/([^/]+)$
RewriteCond %{DOCUMENT_ROOT}/%1.php !-f
RewriteRule ^(.*)$ /404.php [L]

Як це працює:
Перша умова:

RewriteCond %{REQUEST_URI} ^/([^/]+)$ — перевіряє, чи є запит до URL вигляду /url.
RewriteCond %{DOCUMENT_ROOT}/%1.php -f — перевіряє, чи існує файл url.php у кореневій директорії.
Якщо умови виконуються, URL перенаправляється на відповідний файл PHP.

Друга умова:

Якщо файл url.php не існує, переадресовуємо запит на 404.php.

Додатково:

Переконайтеся, що у вас ввімкнений модуль mod_rewrite у конфігурації сервера Apache.
Якщо 404.php повинен знаходитися у певному підкаталозі, змініть шлях у відповідному правилі.

Помилка 500 Internal Server Error зазвичай виникає через помилки у конфігурації .htaccess. Давайте перевіримо код і виправимо можливі проблеми.
Оновлений .htaccess файл

RewriteEngine On

# Якщо файл або директорія існують, пропускаємо запит
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

# Перевіряємо, чи є запит типу /url
RewriteCond %{REQUEST_URI} ^/([^/]+)$
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.*)$ /$1.php [L]

# Якщо файл не існує, переадресовуємо на 404.php
RewriteCond %{REQUEST_URI} ^/([^/]+)$
RewriteCond %{DOCUMENT_ROOT}/$1.php !-f
RewriteRule ^(.*)$ /404.php [L]

Зміни:

Перша перевірка:

 Додано правило, яке дозволяє серверу обробляти запити до існуючих файлів та директорій без втручання mod_rewrite.

Перевірка імен файлів:

Забезпечено правильну перевірку на існування файлу PHP.

Скориговано умови:

Умова RewriteCond %{DOCUMENT_ROOT}/%1.php -f правильно обробляє файли.

Дії для виправлення:
Перевірте наявність модуля mod_rewrite:

У файлі конфігурації Apache (зазвичай httpd.conf або apache2.conf), переконайтеся, що модуль увімкнено:
sudo a2enmod rewrite
sudo systemctl restart apache2

Перевірте дозволи на файли:

Усі файли та директорії повинні мати відповідні права доступу. Наприклад:
chmod 644 *.php

Увімкніть відображення помилок Apache.
Увімкніть журнал помилок, щоб побачити точну причину:

LogLevel debug
ErrorLog ${APACHE_LOG_DIR}/error.log

Перевірте конфігурацію Apache
Переконайтеся, що віртуальний хост дозволяє використання .htaccess:

<Directory /path/to/your/site>
    AllowOverride All
</Directory>

Після внесення змін перезапустіть сервер Apache:

sudo systemctl restart apache2

Якщо проблема залишається, перегляньте журнал помилок Apache (/var/log/apache2/error.log або аналогічний залежно від вашої ОС) для детального діагностування.

Стрілкові функції в JavaScript

Стрілкові функції в JavaScript – це не просто скорочений синтаксис, а справжні магічні стріли, які можуть зробити ваш код більш читабельним та зручним. Ось декілька цікавих речей, які ви можете робити з ними:

Короткі функції з одним виразом: Стрілкові функції ідеально підходять для коротких функцій, які повертають один результат. Наприклад:

    const numbers = [1, 2, 3, 4, 5];
    const squared = numbers.map((num) => num ** 2);
    console.log(squared); // Виведе [1, 4, 9, 16, 25]

    Callback-функції: Вони дуже зручні для використання в методах масивів, таких як mapfilterreduce:

    const numbers = [1, 2, 3, 4, 5];
    const squared = numbers.map((num) => num ** 2);
    console.log(squared); // Виведе [1, 4, 9, 16, 25]
    

    Лексичне прив’язування this: Стрілкові функції автоматично прив’язують this до контексту, в якому вони були створені. Це уникне багатьох проблем, зокрема при роботі з об’єктами та подіями.

    Ланцюги обіцянок (Promises): Стрілкові функції можна використовувати в асинхронних операціях:

    const fetchData = async () => {
        try {
            const response = await fetch('https://api.example.com/data');
            const data = await response.json();
            console.log(data);
        } catch (error) {
            console.error('Something went wrong:', error);
        }
    };
    

    Параметри за замовчуванням та розпакування: Ви можете використовувати параметри за замовчуванням та розпаковування:

    const greet = (name = 'Friend') => `Hello, ${name}!`;
    console.log(greet()); // Виведе "Hello, Friend!"
    

    Отже, стрілкові функції – це не просто стріли, вони – ваші надійні помічники у світі JavaScript! 🚀1 2 3 4 5.

    How to install SSH2 extension for PHP 7.4

    If You have an error like: Call to undefined function ssh2_connect() that’s mean that in your PHP not installed ssh2 extension.

    Install this extension is very simple, in Ubuntu Linux or other Debian based distribution just use the command:

    sudo apt install php7.4-ssh2

    This command will install ssh2 extension to Your PHP 7.4. If you use other PHP version, just change number in this command to Your version.

    Create first program “Hello World” on Assembler in Linux

    To create program on Assembler in Linux operating system we need compiler for x86 architecture named nasm

    sudo apt install nasm

    To compile program in file hello.asm use commands:

    nasm -felf64 hello.asm
    ld hello.o
    

    To start compiled program use command:

    ./a.out

    Nov let’s create our program in file hello.asm using text editor vim

    vim hello.asm

    Here is the full code of program:

    message:
    	db	"Hello World!", 10
    
    _start:
    	mov	rax, 1
    	mov	rdi, 1
    	mov	rsi, message
    	mov	rdx, 14
    	syscall
    
    	mov	rax, 60
    	syscall
    
    	section .data
    
    global _start
    
    section .text

    In first two lines we create some label which contains some directive db width string “Hello World!“, and last symbol 10line feed. Directive is like variables in high level programming languages.

    Directive db can use 1 byte for writing information and can write constants from -128 to 255 and can write symbols and strings.

    Next create label _start: and width command mov we write some data in processor address (register):

    mov rax, 1 – move 1 in register rax – in this string we call data recording.
    mov rdi, 1 – This register response for input and output stream. When we send 1 in register rdi we say processor to work width standard output stream.
    mov rsi, message – we write address of our string in register rsi.
    mov rdx, 14 – we write count bytes of our string in register rdx.

    Next we make system call width command syscall.

    mov rax, 60 – we put number 60 in register rax – this is system call for exit.

    And again make system call width command syscall.

    At the end of program we run command section .data

    Width command global _start we run our program from label _start.

    Width command section .text we declare text part of our code

    How to use Match in PHP 8

    In PHP 8, the match expression was introduced as a more concise and powerful alternative to the switch statement. The match expression allows you to perform pattern matching against a value and execute code based on the matched pattern.

    Here’s the basic syntax of the match expression:

    match ($value) {
        pattern_1 => expression_1,
        pattern_2 => expression_2,
        // more patterns and expressions...
        pattern_n => expression_n,
        default => expression_default
    };

    Here’s how it works:

    • The $value is the expression that you want to match against.
    • pattern_1, pattern_2, and pattern_n are the patterns you want to match against the value. These can be literal values, constants, or expressions.
    • expression_1, expression_2, and expression_n are the expressions that will be executed if the corresponding pattern matches.
    • default is an optional keyword that specifies the default case when none of the patterns match. expression_default is the expression executed in the default case.

    The match expression evaluates the value and compares it against each pattern in order. If a pattern matches, the corresponding expression is executed, and the match expression completes. If none of the patterns match, the default case (if provided) is executed. If no default case is provided and no pattern matches, a MatchError is thrown.

    Here’s an example to illustrate the usage of the match expression:

    $result = match ($value) {
        0 => 'Zero',
        1 => 'One',
        2, 3 => 'Two or Three',
        4, 5, 6 => 'Four, Five, or Six',
        default => 'Other'
    };

    In this example, the value of $value is matched against different patterns, and the corresponding expressions are executed based on the match. The result is assigned to the variable $result.

    The match expression in PHP 8 provides a more expressive and concise way to perform pattern matching, making your code easier to read and maintain.

    Disable exec, shell_exec, system, popen and Other PHP Functions To Improve Security

    PHP has a lot of functions which can be used to crack your server if not used properly. You can set list of functions in php.ini using disable_functions directive. This directive allows you to disable certain functions for security reasons. It takes on a comma-delimited list of function names.

    Open a terminal application or login to your server over the ssh session using ssh command. Open php.ini file using a text editor such as vim command or nano command:

    sudo nano /etc/php/8.0/fpm/php.ini

    Find disable_functions and set new list as follows:

    disable_functions =exec,passthru,shell_exec,system,proc_open,popen,curl_exec,curl_multi_exec,parse_ini_file,show_source

    We also recommend to disable allow_url_include and allow_url_fopen for security reasons:

    allow_url_fopen=Off
    allow_url_include=Off

    Restart PHP with command:

    systemctl restart php8.0-fpm

    Node.js – Lesson 5: Create Web-server application

    First create file app.js:

    const express = require("express");
    const app = express();
    const port = 8000;
    
    app.listen(port, () => {
        console.log("Server work on "+port); 
    });

    In this code we require Express framework that provides a robust set of features for web and mobile applications. Define class app – our main application class and port – default server port.

    We can start our server using command:

    npm run start

    But now our server can not do nothing, ot only write in console text: “Server work on port 8000“. Let’s create routing and say our server how to work with Url and write text to Web-browser.

    First create folder “routes” and file “routes/index.js” with code:

    const mainRoutes = require('./main');
    
    module.exports = function(app) {
        mainRoutes(app);
    }

    Now create file “routes/main.js“:

    module.exports = function(app) {
        app.get('/', (req, res) => {
            res.end('main');
        });
    }

    And the last – in file “app.js” require our routes – before app.listen insert this command: require(“./routes”)(app);

    const express = require("express");
    const app = express();
    const port = 8000;
    
    require("./routes")(app); // require /routes/index.js 
    
    app.listen(port, () => {
        console.log("Server work on "+port); 
    });

    Start program in development mode:

    npm run dev

    Run Web-browser and open http://localhost:8000:

    Similarly you can create /about, /contact or any other route on your NodeJS Web-site.

    Apache Error .htaccess: RewriteEngine not allowed here

    When you try to enable option RewriteEngine on in .htaccess file you can get error:

    /var/www/html/.htaccess: RewriteEngine not allowed here

    In this way you need to enable AllowOverride All option.

    Go to /etc/apache2/sites-available and edit 000-default.conf (or other conf file of your website):

    sudo nano /etc/apache2/sites-available/000-default.conf

    Add next block to this file:

    <Directory />
            AllowOverride All
    </Directory>

    Your config file will be look’s like this:

    <VirtualHost *:80>
            DocumentRoot /var/www/html
    
            <Directory />
                AllowOverride All
            </Directory>
    </VirtualHost>

    Save configuration file and restart apache2

    sudo systemctl restart apache2