Статья

📘 Глава 13. Подключение к MySQL и SQL-запросы в PHP

🧩 Что нужно

  • Установленный MySQL (или MariaDB)

  • Доступ к базе (логин, пароль, имя БД)

  • Таблица для хранения данных


📦 1. Подключение к базе данных

Самый простой способ — через mysqli:

$mysqli = new mysqli("localhost", "root", "password", "guestbook");

if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

⚠️ Всегда проверяй, удалось ли подключение!


🛠 2. Создание таблицы сообщений

Выполни этот SQL в phpMyAdmin или через консоль:

CREATE TABLE messages (
    id INT AUTO_INCREMENT PRIMARY KEY,
    author VARCHAR(100) NOT NULL,
    text TEXT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

💾 3. Сохранение данных в базу

$stmt = $mysqli->prepare("INSERT INTO messages (author, text) VALUES (?, ?)");
$stmt->bind_param("ss", $author, $text);

$author = $_POST["author"];
$text = $_POST["text"];
$stmt->execute();

📥 4. Получение сообщений

$result = $mysqli->query("SELECT * FROM messages ORDER BY created_at DESC");

while ($row = $result->fetch_assoc()) {
    echo "<p><strong>" . htmlspecialchars($row["author"]) . ":</strong> "
        . htmlspecialchars($row["text"]) . "</p>";
}

📌 Полный пример — index.php

<?php
$mysqli = new mysqli("localhost", "root", "password", "guestbook");
if ($mysqli->connect_error) die("Connection failed: " . $mysqli->connect_error);

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $author = trim($_POST["author"]);
    $text = trim($_POST["text"]);

    if ($author && $text) {
        $stmt = $mysqli->prepare("INSERT INTO messages (author, text) VALUES (?, ?)");
        $stmt->bind_param("ss", $author, $text);
        $stmt->execute();
        header("Location: " . $_SERVER["PHP_SELF"]);
        exit;
    } else {
        echo "Please fill in both fields.";
    }
}
?>

<form method="post">
    <input type="text" name="author" placeholder="Your name">
    <br>
    <textarea name="text" placeholder="Your message"></textarea>
    <br>
    <button type="submit">Send</button>
</form>

<hr>

<?php
$result = $mysqli->query("SELECT * FROM messages ORDER BY created_at DESC");

while ($row = $result->fetch_assoc()) {
    echo "<p><strong>" . htmlspecialchars($row["author"]) . ":</strong> "
        . htmlspecialchars($row["text"]) . "</p>";
}
?>

✅ Что ты изучил:

  • Подключение к MySQL через mysqli

  • prepare() и bind_param() для защиты от SQL-инъекций

  • Добавление и вывод данных

  • SQL-запросы


В следующей главе — переход от mysqli к PDO, более гибкому и мощному способу работы с базой.

PHP
Для ответа вы можете авторизоваться