1

При вводе товара в БД появляются пустые поля (кроме первичного ключа).

В чем ошибка?

add2cat.php:

<?
require "secure/session.inc.php";
require "../inc/db.inc.php";
?>
<html>
<head>
    <title>Форма добавления товара в каталог</title>
</head>
<body>
    <form action="save2cat.php" method="post">
        <p>Название: <input type="text" name="title" size="100">
        <p>Автор: <input type="text" name="author" size="50">
        <p>Год издания: <input type="text" name="pubyear" size="4">
        <p>Цена: <input type="text" name="price" size="6"> руб.
        <p><input type="submit" value="Добавить">
    </form>
</body>
</html>

db.inc.php:

<?php
header('Content-Type: text/html; charset=utf-8');
define ('DB_HOST', 'localhost');
define ('DB_LOGIN', 'root');
define ('DB_PASSWORD', '');
define ('DB_NAME', 'eshop');
define ('ORDERS_LOG', 'orders.log');
// Корзина покупателя
$basket = array();
//Кол-во товаров в корзине покупателя
$count = 0;
$link = mysqli_connect(DB_HOST, DB_LOGIN, DB_PASSWORD, DB_NAME) or die(mysqli_connect_error());

lib.inc.php:

<?php
function clearInt($data){
    return abs((int)$data);
}

function clearStr($data){
    global $link;
    return mysqli_real_escape_string($link, trim(strip_tags($data)));
}

function addItemToCatalog($title, $author, $pubyear, $price){
    global $link;
    $sql = "INSERT INTO catalog (title, author, pubyear, price)
                   VALUES (?, ?, ?, ?)";
    if(!$stmt = mysqli_prepare($link, $sql))
        return false;
    mysqli_stmt_bind_param($stmt, "ssii", $title, $author, $pubyear, $price);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_close($stmt);
    return true;
}

save2cat.php:

<?php
    // подключение библиотек
    require "secure/session.inc.php";
    require "../inc/lib.inc.php";
    require "../inc/db.inc.php";

    $author = clearStr($POST['author']);
    $title = clearStr($POST['title']);
    $pubyear = clearInt($POST['pubyear']);
    $price = clearInt($POST['price']);

    if(!addItemToCatalog($title, $author, $pubyear, $price)){
        echo 'Произошла ошибка при добавлении товара';
    }else{
        header('Location: add2cat.php');
        exit;
    }
?>
4
  • 1
    Скорее всего кавычки забыл вокруг строк.
    – Vesper
    13 июл 2015 в 13:07
  • @Vesper VALUES (?, ?, ?, ?) - тут ?
    – Orange-Man
    13 июл 2015 в 13:11
  • @Вадим нет, строка с prepared statement выглядит нормальной.
    – Regent
    13 июл 2015 в 13:20
  • Почитал немного - нет, говорят нельзя кавычки тут ставить. Тогда не знаю, вроде на первый взгляд ошибок в коде нет.
    – Vesper
    13 июл 2015 в 13:21

2 ответа 2

2

Правильное название массива - не $POST, а $_POST.

1
  • Как я мог допустить такую ошибку ... Спасибо тебе большое !
    – Orange-Man
    13 июл 2015 в 13:50
0

пользовательская функция clearStr экранирует строку, если прилетает имя O'Neill например, то в базу оно полетит со слешем т.е.: O\'Neill т.к. отправка происходит через подготовленный запрос. Но экранирующий слеш уберётся (будет уместен) при отправке через mysqli_query()

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.