Làm cách nào để sửa lỗi này: khóa mảng không xác định nhiều biến trên tệp PHP

lập trình


Tôi đang học PHP và MySQL và tôi đang thực hiện dự án thứ 2, lần này là một dự án quan trọng đối với tôi.. một thương mại điện tử

Tôi đang làm việc 24/7 về vấn đề này và tôi gặp nhiều lỗi và tôi tìm kiếm nhiều nhất có thể và tôi dần dần sửa chữa mọi thứ, nhưng bây giờ tôi đang mắc kẹt ở vấn đề này, tôi cho rằng đây là lỗi kết nối hoặc lỗi gì đó về mảng. Tôi sẽ chuyển sang vấn đề.

Connected successfully!
Warning: Undefined array key "sku" in C:\xampp\htdocs\prueba\add.php on line 25

Warning: Undefined array key "name" in C:\xampp\htdocs\prueba\add.php on line 26

Warning: Undefined array key "price" in C:\xampp\htdocs\prueba\add.php on line 27

Warning: Undefined array key "productType" in C:\xampp\htdocs\prueba\add.php on line 28

Warning: Undefined array key "size" in C:\xampp\htdocs\prueba\add.php on line 29

Warning: Undefined array key "weight" in C:\xampp\htdocs\prueba\add.php on line 30

Warning: Undefined array key "height" in C:\xampp\htdocs\prueba\add.php on line 31

Warning: Undefined array key "width" in C:\xampp\htdocs\prueba\add.php on line 32

Warning: Undefined array key "length" in C:\xampp\htdocs\prueba\add.php on line 33

Fatal error: Uncaught mysqli_sql_exception: Duplicate entry '0' for key 'PRIMARY' in C:\xampp\htdocs\prueba\add.php:40 Stack trace: #0 C:\xampp\htdocs\prueba\add.php(40): mysqli->query('INSERT INTO pro...') #1 {main} thrown in C:\xampp\htdocs\prueba\add.php on line 40

Mã của tôi: add.php

<?php

ini_set('display_errors', 1);
error_reporting(E_ALL);

// Connect to database
include ('config/connect.php');
//$result = mysqli_query($conn,'select * from products')

/*
$nombreSKU = $_POST['SKU'];
$nombreName = $_POST['name'];
$nombrePrice = $_POST['price']; // pass = PASSWORD
$nombreProductType = $_POST['productType'];
$nombreSize = $_POST['size'];
$nombreWeight = $_POST['weight'];
$nombreHeight = $_POST['height'];
$nombreWidth = $_POST['width'];
$nombreLength = $_POST['length'];
*/


//declare 
$sku = $_POST['sku'];
$name = $_POST['name'];
$price = $_POST['price'];
$productType = $_POST['productType'];
$size = $_POST['size'];
$weight = $_POST['weight'];
$height = $_POST['height'];
$width = $_POST['width'];
$length = $_POST['length'];

$sql = "INSERT INTO products (`SKU`, `NAME`, `PRICE`, `PRODUCTTYPE`, `SIZE`, `WEIGHT`, `HEIGHT`, `WIDTH`, `LENGTH`)
VALUES ('$sku', '$name', '$price', '$productType', '$size', '$weight', '$height', '$width', '$length');";



if ($conn->query($sql) === TRUE) {
	echo "ADDED: " . $sku . ", " . $name . ", " . $price, ".$productType.", ".$size.", ".$weight.", ".$height.", ".$width.", ".$length.";		
} else {
	echo "Error: " . $sql . "<br>" . $conn->error;
}





// Check connection
if($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully!";


$conn->close();
header("Location: ./index.php", TRUE, 301);
exit();

?>

Mã connect.php của tôi:

<?php

$host = 'localhost';   // host name
$username = 'username';   // database username
$password = '';  // database password (none)
$databaseName = 'dbtest';   // database name
$tblName = 'products';   // name of the unique table 'products'

// Create connection
$conn = new mysqli('localhost','root','','dbtest');

// Check connection
if($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully!";
?>

Mã index.HTML của tôi:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ADD PRODUCTS!!</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
 <!-- <div class="header"></div>Esto lo puso el pibe del video Paul Crud --> 

    <header class="header">
    <h1>Product Add</h1>
    <nav class="nav">
        <input class="headerbutton" type="submit" form="product_form" name="submit" id="submit" value="Save">
        <a class="headerbutton" href="./index.php">Cancel</a>
    </nav>
  </header>


  <main class="main">
    <form id="product_form" action="add.php" method="POST">
        <label class="prodlabel" for="SKU">SKU </label>
        <input class="prodinput" title="Please enter your product SKU." type="text" id="sku" name="sku" maxlength="24" pattern="[A-Za-z0-9]+" required=""><br>
        <label class="prodlabel" for="name">Name </label>
        <input class="prodinput" title="Please enter product name." type="text" id="name" name="name" maxlength="12" required=""><br>
        <label class="prodlabel" for="price">Price ($) </label>
        <input class="prodinput" title="Please enter product price." type="number" id="price" name="price" min="0.00" max="10000.00" step="0.01" required=""><br>
        <label class="prodlabel" for="productType">Type </label>
        <select class="prodinput" id="productType" name="productType" size="1" required onchange="checkInput(this)">
          <option value="" selected disabled>Choose one:</option>
          <option value="DVD">DVD-disc</option>
          <option value="Book">Book</option>
          <option value="Furniture">Furniture</option>
      </select><br>
      <div id="DVD" style="display: none;">
        <label class="prodlabel" for="DVD">Size (MB) </label>
        <input class="prodinput" type="number" id="size" name="size" min="1" max="8540" maxlength="4"><br>
        Please provide disc space in MB.
      </div>

      <div id="Book" style="display: none;">
        <label class="prodlabel" for="Book">Weight (KG) </label>
        <input class="prodinput" type="number" id="weight" name="weight" min="1" max="9999" maxlength="4"><br>
        Please provide weight in Kg.
      </div>

      <div id="Furniture" style="display: none;">
        <label class="prodlabel" for="Height">Height (CM) </label>
        <input class="prodinput" type="number" id="height" name="height" min="1" max="999" maxlength="3"><br>
        <label class="prodlabel" for="Width">Width (CM) </label>
        <input class="prodinput" type="number" id="width" name="width" min="1" max="999" maxlength="3"><br>
        <label class="prodlabel" for="Length">Length (CM) </label>
        <input class="prodinput" type="number" id="length" name="length" min="1" max="999" maxlength="3"><br>
        Please provide dimensions in HxWxL format
      </div>
    </form>
  </main>
</body>
</html>

Mã tab khác của tôi: index.php

<?php

// MYSQL connection
include ('config/connect.php');

//$result = mysqli_query($conn,'select * from products')
//or die("Error: " . mysqli_error($conn));

// fetch ? 
$result = @mysqli_query($conn, "SELECT * FROM products") or die("Error: " . mysqli_error($conn));

// delete
if(isset($_POST['chk_id']))
{
    $arr = $_POST['chk_id'];
    foreach ($arr as $id) {
        @mysqli_query($conn,"DELETE FROM products WHERE id = " . $id);
    }
    $msg = "Deleted Successfully!";
    header("Location: index.php?msg=$msg");
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Product List</title>
  <link rel="stylesheet" href="./style.css">
</head>

<body>
  <header class="header">
    <h1>Product List</h1>
    <nav class="nav">
      <a href="./add.php">
        <input type="button" value="ADD" class="headerbutton">
      </a>
      <form action="index.php" method="POST">
        <button id="delete-product-btn" class="headerbutton" type="submit">MASS DELETE</button>
      
    </nav>
  </header>
  <main class="main">
    <div class="productList">
          <div class="product">
              <!--- name= chk-id    ORIGINAL ERA ASI, yo puse SKU  !--->
            <input class="delete-checkbox" name="chk_id[]" type="checkbox" value="<?= $row['id'];?>"/>
            <p><?= $row['sku']; ?></p>
            <p><?= $row['name']; ?></p>
            <p><?= $row['price']. " $"; ?></p>
            <p>
            <?php 
            if ($row['size'] > 0)
              echo "Size: " . $row['size'] . " MB"; 
            if ($row['weight'] > 0)
              echo "Weight: " . $row['weight'] . "KG"; 
            if ($row['height'] > 0) 
            echo "Dimension: " . $row['height'] . "x" . $row['width'] . "x" . $row['length'] ; 
            ?>
            </p>
          </div>
        <?php
        ?>
    </div>
  </form>
  </main>
</html>

Và sau đó tôi có các kiểu mà tôi sẽ không thêm vì phần này đã đủ dài rồi.

Những gì tôi đã thử:

Tôi đã thử tìm trên Google tất cả các lỗi, sửa những gì tôi tìm thấy trên Google, nhưng sau đó một lỗi khác lại xuất hiện và đó là một vòng lặp không bao giờ kết thúc

Tôi hiện đang mượn trợ giúp từ W3Schools Online cho các hướng dẫn về PHP và MYSQL. Họ đang giúp đỡ rất nhiều, nhưng tôi không tìm thấy trợ giúp liên quan đến lỗi ở đó và các lỗi từ Google khác rất nhiều so với lỗi của tôi, vì vậy tôi không thể tìm ra cách khắc phục phù hợp cho mã của mình

Giải pháp 1

Giải pháp 2

Bạn cần kiểm tra xem $_POST[] các ô mảng được đặt trước khi đọc chúng.
Vì vậy, hãy cập nhật tuyên bố của bạn như sau:

//tuyên bố
if(isset($_POST[‘sku’]))
$sku = $_POST[‘sku’];
if(isset($_POST[‘name’]))
$name = $_POST[‘name’];
if(isset($_POST[‘price’]))
$giá = $_POST[‘price’];

コメント

タイトルとURLをコピーしました