проблемы с неопределенным индексом с php mysql - объяснение, необходимое для нового ученика

0

(Мне просто нужен конкретный ответ, почему это происходит)

Я изучаю PHP и MySQL здесь, в StackOverflow, и большую часть времени я слишком возбуждаюсь и объединяю вещи, которые я получил здесь. Хотя я пытаюсь понять вещи непосредственно из ошибок, которые я совершаю, есть еще некоторые вещи, которые я не могу решить самостоятельно. Самая последняя проблема:

Я долгое время работал над примером, и я постоянно получаю следующее сообщение об ошибке после нажатия кнопки "Добавить новую запись".

Хотя у меня нет проблем и я не получил никаких ошибок, когда у меня было только 3 объявленных переменных, когда я добавил больше входных тегов() на свою страницу, я начал получать эти сообщения об ошибках, и мой запрос на вставку не смог пройти.

Ниже приведены ошибки, которые появляются после нажатия кнопки "Добавить новую запись":

Примечание. Неопределенный индекс: buyprice в C:\xampp\htdocs\sppap\create.php в строке 54

Примечание. Неопределенный индекс: брутто в C:\xampp\htdocs\sppap\create.php в строке 76

и вот мой PHP и соответствующий HTML:

PHP

<?php
    require_once 'config.php';
    $brand = $generic = $wgtvol = $unit =  $manufacturer = "";
    $buyprice = $sellprice = $grosssale = "";

    $brand_err = $generic_err = $wgtvol_err = $unit_err = $manufacturer_err = $buyprice_err = $sellprice_err = $grosssale_err = ""; 

    if($_SERVER["REQUEST_METHOD"] == "POST"){
        $input_brand = trim($_POST["brand"]);
        if(empty($input_brand)){
            $brand_err = '<b style="color: #960303; font-size: 160%">Please enter the brand name of the product.</b>';
        } else{
            $brand = $input_brand;
        }
        $input_generic = trim($_POST["generic"]);
        if(empty($input_generic)){
            $generic_err = '<b style="color: #960303; font-size: 160%">Please enter the generic name of the product.</b>';
        } else{
            $generic = $input_generic;
        }
        $input_wgtvol = trim($_POST["wgtvol"]);
        if(empty($input_wgtvol)){
            $wgtvol_err = '<b style="color: #960303; font-size: 160%">Please enter the weight or volume of the product.</b>';
        } else{
            $wgtvol = $input_wgtvol;
        }

        $input_manufacturer = trim($_POST["manufacturer"]);
        if(empty($input_manufacturer)){
            $manufacturer_err = '<b style="color: #960303; font-size: 160%">Please enter the manufacturer of the product.</b>';
        } else{
            $manufacturer = $input_manufacturer;
        }
        $input_unit = trim($_POST["unit"]);
        if(empty($input_unit)){
            $unit_err = '<b style="color: #960303; font-size: 160%">Please choose a measurement unit of the product.</b>';
        } else{
            $unit  = $input_unit ;
        }
        $input_buyprice = trim($_POST["buyprice"]);
        if(empty($input_buyprice)){
            $buyprice_err = '<b style="color: #960303; font-size: 160%">Please enter the buy price of the product.</b>';
        } else{
            $buyprice = $input_buyprice;
        }
        $input_sellprice = trim($_POST["sellprice"]);
        if(empty($input_sellprice)){
            $sellprice_err = '<b style="color: #960303; font-size: 160%">Please enter the sell price of the product.</b>';
        } else{
            $sellprice = $input_sellprice;
        }
        $input_grosssale = trim($_POST["grosssale"]);
        if(empty($input_grosssale)){
            $grosssale_err = '<b style="color: #960303; font-size: 160%">This field is suppose to auto-generate after typing the buy price and the sell price.<br>There is no need to manually enter an amount into this field.</b>';
        } else{
            $grosssale = $input_grosssale;
        }
        $generic = $brand = $wgtvol = $unit = $manufacturer = $buyprice = $sellprice = $grosssale = "";
        if(empty($generic_err) && empty($brand_err) && empty($wgtvol_err) && empty($unit_err) && empty($manufacturer_err) && empty($buyprice_err) && empty($sellprice_err) && empty($grosssale_err)){
            $sql = "INSERT INTO productslist (generic, brand, wgtvol, unit, manufacturer, buyprice, sellprice, grosssale) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
            if($stmt = mysqli_prepare($link, $sql)){
                mysqli_stmt_bind_param($stmt, "ssssssss", $param_generic, $param_brand, $param_wgtvol, $param_unit, $param_manufacturer, $param_buyprice, $param_sellprice, $param_grosssale);
                $param_generic = $input_generic;
                $param_brand = $input_brand;
                $param_wgtvol = $input_wgtvol;
                $param_unit = $input_unit;
                $param_manufacturer = $input_manufacturer;
                $param_buyprice = $input_buyprice;
                $param_sellprice = $input_sellprice;
                $param_grosssale = $input_grosssale;
                if(mysqli_stmt_execute($stmt)){
                    header("location: index.php");
                    exit();
                } else{
                    echo "Something went wrong. Please try again later.";
                }
            }
            mysqli_stmt_close($stmt);
        }
        mysqli_close($link);
    }
?>

HTML

<form class="form-wrapper" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
    <div class="form-group <?php echo (!empty($brand_err)) ? 'has-error' : ''; ?>">
        <label>Brand Name</label>
        <input type="text" name="brand" class="form-control" value="<?php echo $brand; ?>" />
        <span class="help-block"><?php echo $brand_err;?></span>
    </div>
    <div class="form-group <?php echo (!empty($generic_err)) ? 'has-error' : ''; ?>">
        <label>Generic Name</label>
        <input type="text" name="generic" class="form-control" value="<?php echo $generic; ?>" />
        <span class="help-block"><?php echo $generic_err;?></span>
    </div>
    <div class="form-group <?php echo (!empty($wgtvol_err)) ? 'has-error' : ''; ?>">
        <div class="input-group">
            <label class="black-text">Weight / Volume</label>
            <input type="number" step="0.01" maxlength="7" class="form-control digitOnly pull-left" id="wgtvol" name="wgtvol" value="<?php echo $wgtvol; ?>" />
            <label class="sr-only black-text">Unit</label>
            <select  name="unit" class="form-control pull-left" id="unit" type="text"  >
                <option disabled value="">select</option>
                <option value="mg"> mg </option>
                <option value="gram(s)"> gram(s) </option>
                <option value="ml"> ml </option>
                <option value="liter(s)">liter(s)</option>
                <option value="dl"> dl </option>
                <option value="cc"> cc </option>
                <option value="pc(s)"> pc(s) </option>
                <option value="fl oz">fl oz</option>
                <option value="gal">gal</option>
            </select>
        </div>
    </div>
    <div class="form-group <?php echo (!empty($manufacturer_err)) ? 'has-error' : ''; ?>">
        <label>Manufacturer</label>
        <input type="text" name="manufacturer" class="form-control" value="<?php echo $manufacturer; ?>" />
        <span class="help-block"><?php echo $manufacturer_err;?></span>
    </div>
    <div class="form-group <?php echo (!empty($buyprice_err)) ? 'has-error' : ''; ?>">
        <label>Buy Price</label>
        <input type="number" step="0.01" maxlength="7" class="form-control digitOnly name="buyprice" class="form-control" value="<?php echo $buyprice; ?>"  />
        <span class="help-block"><?php echo $buyprice_err;?></span>
    </div>=
    <div class="form-group <?php echo (!empty($sellprice_err)) ? 'has-error' : ''; ?>">
        <label>Sell Price</label>
        <input type="number" step="0.01" maxlength="7" class="form-control digitOnly" name="sellprice" value="<?php echo $sellprice; ?>"  />
        <span class="help-block"><?php echo $sellprice_err;?></span>
    </div>
    <div class="form-group <?php echo (!empty($grosssale_err)) ? 'has-error' : ''; ?>">
        <label>Gross Sale</label>
        <input disabled type="number" maxlength="7" class="form-control digitOnly" name="grosssale" value="<?php echo $grosssale; ?> "  />
        <span class="help-block"><?php echo $grosssale_err;?></span>
    </div>
    <input type="submit" class="btn btn-primary" value="Add New Record" />
    <a href="index.php" class="btn btn-default">Cancel</a>
</form>
Теги:

1 ответ

0

Вы никогда не закрывали атрибут class в своем HTML-элементе, чтобы name было настроено неправильно. См. Этот бит:

class="form-control digitOnly name="buyprice"

Вам нужно закрыть этот class с name " before name. Я не уверен, что digitOnly - это другой класс или некоторый атрибут HTML5.

Думаю, вы хотели:

class="form-control digitOnly" name="buyprice"

Вы также должны отступать от своего кода, чтобы его было легче читать.

Элемент grosssale disabled поэтому он не будет отправлен. Вы можете прочитать больше здесь, Введенные входы формы не отображаются в запросе.

  • 0
    нет, digitOnly - это еще один отдельный класс. Мне просто интересно, нужно ли мне переопределять мои переменные, в которых есть уведомления об ошибках. и мой <input> с оптовыми продажами предназначен для отключения, так как он автоматически появится после ввода цены покупки и продажи ..
  • 0
    Ошибка в том, что $_POST не имеет индекса с этими двумя именами. Первый будет исправлен путем изменения кавычек. Вам нужно разобраться, как работает ваш JS. Как <input disabled , не будет отправлен. Вы можете сделать print_r($_POST); чтобы увидеть все значения, которые имеет ваш POST ... или вы можете открыть консоль разработчика, перейти на вкладку сети и щелкнуть отправляющий запрос. Есть опция form data , которая покажет все.
Показать ещё 7 комментариев

Ещё вопросы

Сообщество Overcoder
Наверх
Меню