【解決方法】このエラーを修正するにはどうすればよいですか: PHP ファイルの未定義の配列キーの複数の変数

プログラミングQA


私は PHP と MySQL を学んでいて、2 番目のプロジェクトに取り組んでいます。今回は私にとって大きなプロジェクトです。e コマースです。

私はこれに24時間年中無休で取り組んでおり、複数のエラーが発生し、可能な限りグーグルで調べてゆっくりと修正しましたが、今はこれで行き詰まっています。これは接続のエラーか配列に関する何かだと思います。 本題に飛びます。

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

私のコード: 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();

?>

私のconnect.phpコード:

<?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!";
?>

私の index.HTML コード:

<!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>

私の他のタブコード: 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>

そして、スタイルがありますが、これはすでに十分に長いので追加しません。

私が試したこと:

すべてのエラーをグーグルで調べて、グーグルで見つけたものを修正しようとしましたが、別のエラーがジャンプして、終わりのないループです

私は現在、W3Schools Online から PHP と MYSQL のチュートリアルを借りています。 彼らは大いに役立っていますが、そこにはエラーに関連するヘルプが見つかりません。また、Google からのエラーは私のものとは大きく異なるため、自分のコードの適切な修正を見つけることができません。

解決策 1

ここを参照してください: javascript – Post を使用した PHP フォーム. エラー: 未定義の配列キーです。 ただし、getを使用すると機能します。 (w3schoolsの例)[^]

_POST の代わりに _GET を使用するつもりだったのではないかと思います

解決策 2

$_POST かどうかを確認する必要があります[] 配列セルは、読み取る前に設定されます。
したがって、宣言を次のように更新します。

//宣言する
if(isset($_POST[‘sku’])))
$sku = $_POST[‘sku’];
if(isset($_POST[‘name’])))
$name = $_POST[‘name’];
if(isset($_POST[‘price’])))
$価格 = $_POST[‘price’];

コメント

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