html formdaki tablo dizileri veritabanıındaki ilişkili tablolara aktarmıyor

PHP Programlama dili hakkında tartışmalar, paylaşım ve yardımlaşma forumu.
Cevapla
boty30
Kayıtlı Kullanıcı
Mesajlar: 1
Kayıt: 23.07.2023, 00:20

html formdaki tablo dizileri veritabanıındaki ilişkili tablolara aktarmıyor

Mesaj gönderen boty30 »

Kod: Tümünü seç

<!DOCTYPE html>
<html>
<head>
  <style>
    body {
      font-family: Arial, sans-serif;
    }

    .section {
      margin-bottom: 20px;
    }

    .section h2 {
      margin-bottom: 10px;
    }

    .form-row {
      display: flex;
      align-items: center;
      margin-bottom: 10px;
    }

    .form-row label {
      width: 150px;
    }

    .form-row input,
    .form-row select {
      flex: 1;
      margin-right: 10px;
    }

    .add-button {
      margin-left: 160px;
    }

    table {
      width: 100%;
      border-collapse: collapse;
      margin-top: 20px;
    }

    table th,
    table td {
      padding: 8px;
      border: 1px solid #ddd;
    }

    table th {
      background-color: #f5f5f5;
    }

    .delete-button {
      background-color: #dc3545;
      color: white;
      border: none;
      padding: 5px 10px;
      cursor: pointer;
    }

    .delete-button:hover {
      background-color: #c82333;
    }

    .submit-button {
      background-color: #007bff;
      color: white;
      border: none;
      padding: 10px 20px;
      cursor: pointer;
    }

    .submit-button:hover {
      background-color: #0069d9;
    }

    /* Renkler */
    body {
      background-color: #f8f8f8;
      color: #333;
    }

    .section {
      background-color: #fff;
      border: 1px solid #ddd;
      padding: 20px;
    }

    h2 {
      color: #007bff;
    }

    .form-row label {
      color: #555;
    }

    input[type="text"],
    input[type="number"],
    input[type="tel"],
    input[type="email"],
    textarea {
      border: 1px solid #ddd;
      padding: 8px;
      border-radius: 4px;
    }

    input[type="text"]:focus,
    input[type="number"]:focus,
    input[type="tel"]:focus,
    input[type="email"]:focus,
    textarea:focus {
      outline: none;
      border-color: #007bff;
    }

    .add-button {
      background-color: #007bff;
      color: #fff;
      border: none;
      padding: 8px 16px;
      border-radius: 4px;
      cursor: pointer;
    }

    .add-button:hover {
      background-color: #0069d9;
    }

    table {
      background-color: #fff;
    }

    table th {
      background-color: #f5f5f5;
      color: #333;
    }

    .delete-button {
      background-color: #dc3545;
      color: #fff;
      border: none;
      padding: 4px 8px;
      border-radius: 4px;
      cursor: pointer;
    }

    .delete-button:hover {
      background-color: #c82333;
    }

    .submit-button {
      background-color: #007bff;
      color: #fff;
      border: none;
      padding: 10px 20px;
      border-radius: 4px;
      cursor: pointer;
    }

    .submit-button:hover {
      background-color: #0069d9;
    }
  </style>
</head>
<body>
  <form method="POST" action="fkaydet.php">
    <div class="section">
      <h2>Shipper Details</h2>
      <div class="form-row">
        <label for="shipper-name">Shipper Name:</label>
        <input type="text" id="shipper-name" name="shipper-name">
      </div>
      <div class="form-row">
        <label for="shipper-phone">Phone Number:</label>
        <input type="tel" id="shipper-phone" name="shipper-phone">
      </div>
      <div class="form-row">
        <label for="shipper-address">Address:</label>
        <input type="text" id="shipper-address" name="shipper-address">
      </div>
      <div class="form-row">
        <label for="shipper-email">Email:</label>
        <input type="email" id="shipper-email" name="shipper-email">
      </div>
    </div>

    <div class="section">
      <h2>Receiver Details</h2>
      <div class="form-row">
        <label for="receiver-name">Receiver Name:</label>
        <input type="text" id="receiver-name" name="receiver-name">
      </div>
      <div class="form-row">
        <label for="receiver-phone">Phone Number:</label>
        <input type="tel" id="receiver-phone" name="receiver-phone">
      </div>
      <div class="form-row">
        <label for="receiver-address">Address:</label>
        <input type="text" id="receiver-address" name="receiver-address">
      </div>
      <div class="form-row">
        <label for="receiver-email">Email:</label>
        <input type="email" id="receiver-email" name="receiver-email">
      </div>
    </div>

    <div class="section">
      <h2>Shipment Details</h2>
      <div class="form-row">
        <label for="shipment-type">Type of Shipment:</label>
        <input type="text" id="shipment-type" name="shipment-type">
      </div>
      <div class="form-row">
        <label for="shipment-weight">Weight:</label>
        <input type="number" id="shipment-weight" name="shipment-weight">
      </div>
      <div class="form-row">
        <label for="shipment-courier">Courier:</label>
        <input type="text" id="shipment-courier" name="shipment-courier">
      </div>
      <div class="form-row">
        <label for="shipment-packages">Packages:</label>
        <input type="number" id="shipment-packages" name="shipment-packages">
      </div>
      <div class="form-row">
        <label for="shipment-mode">Mode:</label>
        <input type="text" id="shipment-mode" name="shipment-mode">
      </div>
      <div class="form-row">
        <label for="shipment-product">Product:</label>
        <input type="text" id="shipment-product" name="shipment-product">
      </div>
      <div class="form-row">
        <label for="shipment-quantity">Quantity:</label>
        <input type="number" id="shipment-quantity" name="shipment-quantity">
      </div>
      <div class="form-row">
        <label for="shipment-payment">Payment Mode:</label>
        <input type="text" id="shipment-payment" name="shipment-payment">
      </div>
      <div class="form-row">
        <label for="shipment-freight">Total Freight:</label>
        <input type="number" id="shipment-freight" name="shipment-freight">
      </div>
      <div class="form-row">
        <label for="shipment-carrier">Carrier:</label>
        <input type="text" id="shipment-carrier" name="shipment-carrier">
      </div>
      <div class="form-row">
        <label for="shipment-reference">Carrier Reference No.:</label>
        <input type="text" id="shipment-reference" name="shipment-reference">
      </div>
      <div class="form-row">
        <label for="shipment-departure">Departure Time:</label>
        <input type="text" id="shipment-departure" name="shipment-departure">
      </div>
      <div class="form-row">
        <label for="shipment-origin">Origin:</label>
        <input type="text" id="shipment-origin" name="shipment-origin">
      </div>
      <div class="form-row">
        <label for="shipment-destination">Destination:</label>
        <input type="text" id="shipment-destination" name="shipment-destination">
      </div>
      <div class="form-row">
        <label for="shipment-pickup-date">Pickup Date:</label>
        <input type="date" id="shipment-pickup-date" name="shipment-pickup-date">
      </div>
      <div class="form-row">
        <label for="shipment-pickup-time">Pickup Time:</label>
        <input type="time" id="shipment-pickup-time" name="shipment-pickup-time">
      </div>
      <div class="form-row">
        <label for="shipment-delivery-date">Expected Delivery Date:</label>
        <input type="date" id="shipment-delivery-date" name="shipment-delivery-date">
      </div>
      <div class="form-row">
        <label for="shipment-comments">Comments:</label>
        <textarea id="shipment-comments" name="shipment-comments"></textarea>
      </div>
    </div>


 <div class="section" id="tables">

    <div class="section" id="containers">
      <h2>Containers</h2>
      <div class="form-row">
        <input type="text" class="container-type-input" name="container-type[]" placeholder="Container Type">
        <input type="number" class="container-quantity-input" name="container-quantity[]" placeholder="Container Quantity">
        <input type="text" class="container-attribute-input" name="container-attribute[]" placeholder="Container Attribute">
        <input type="text" class="container-description-input" name="container-description[]" placeholder="Container Description">
        <button type="button" class="add-button" onclick="addContainer()">Add Container</button>
      </div>
    </div>

    <table id="containersTable">
      <thead>
        <tr>
          <th>Container Type</th>
          <th>Container Quantity</th>
          <th>Container Attribute</th>
          <th>Container Description</th>
          <th></th>
        </tr>
      </thead>
      <tbody id="containersTableBody"></tbody>
    </table>

    <div class="section" id="packages">
      <h2>Packages</h2>
      <div class="form-row">
        <input type="number" class="qty-input" name="qty[]" placeholder="Qty.">
        <input type="text" class="piece-type-input" name="piece-type[]" placeholder="Piece Type">
        <input type="text" class="description-input" name="description[]" placeholder="Description">
        <input type="number" class="length-input" name="length[]" placeholder="Length (cm)">
        <input type="number" class="width-input" name="width[]" placeholder="Width (cm)">
        <input type="number" class="height-input" name="height[]" placeholder="Height (cm)">
        <input type="number" class="weight-input" name="weight[]" placeholder="Weight (kg)">
        <button type="button" class="add-button" onclick="addPackage()">Add Package</button>
      </div>
    </div>

    <table id="packagesTable">
      <thead>
        <tr>
          <th>Qty.</th>
          <th>Piece Type</th>
          <th>Description</th>
          <th>Length (cm)</th>
          <th>Width (cm)</th>
          <th>Height (cm)</th>
          <th>Weight (kg)</th>
          <th></th>
        </tr>
      </thead>
      <tbody id="packagesTableBody"></tbody>
    </table>
    </div>

    <button type="submit" class="submit-button">Save</button>
  </form>

  <script>
    var packageList = [];
    var containerList = [];

    function addPackage() {
      var qtyInput = document.querySelector("#packages .qty-input");
      var pieceTypeInput = document.querySelector("#packages .piece-type-input");
      var descriptionInput = document.querySelector("#packages .description-input");
      var lengthInput = document.querySelector("#packages .length-input");
      var widthInput = document.querySelector("#packages .width-input");
      var heightInput = document.querySelector("#packages .height-input");
      var weightInput = document.querySelector("#packages .weight-input");

      if (!qtyInput.value || !pieceTypeInput.value || !descriptionInput.value || !lengthInput.value || !widthInput.value || !heightInput.value || !weightInput.value) {
        alert("Please fill in all fields.");
        return;
      }

      var package = {
        qty: qtyInput.value,
        pieceType: pieceTypeInput.value,
        description: descriptionInput.value,
        length: lengthInput.value,
        width: widthInput.value,
        height: heightInput.value,
        weight: weightInput.value
      };

      packageList.push(package);
      renderPackagesTable();
      clearPackageInputs();
    }

    function deletePackage(index) {
      packageList.splice(index, 1);
      renderPackagesTable();
    }

    function renderPackagesTable() {
      var tableBody = document.getElementById("packagesTableBody");
      tableBody.innerHTML = "";

      packageList.forEach(function(package, index) {
        var row = document.createElement("tr");
        var qtyCell = document.createElement("td");
        var pieceTypeCell = document.createElement("td");
        var descriptionCell = document.createElement("td");
        var lengthCell = document.createElement("td");
        var widthCell = document.createElement("td");
        var heightCell = document.createElement("td");
        var weightCell = document.createElement("td");
        var deleteCell = document.createElement("td");
        var deleteButton = document.createElement("button");

        qtyCell.textContent = package.qty;
        pieceTypeCell.textContent = package.pieceType;
        descriptionCell.textContent = package.description;
        lengthCell.textContent = package.length;
        widthCell.textContent = package.width;
        heightCell.textContent = package.height;
        weightCell.textContent = package.weight;

        deleteButton.textContent = "Delete";
        deleteButton.classList.add("delete-button");
        deleteButton.onclick = function() {
          deletePackage(index);
        };

        deleteCell.appendChild(deleteButton);

        row.appendChild(qtyCell);
        row.appendChild(pieceTypeCell);
        row.appendChild(descriptionCell);
        row.appendChild(lengthCell);
        row.appendChild(widthCell);
        row.appendChild(heightCell);
        row.appendChild(weightCell);
        row.appendChild(deleteCell);

        tableBody.appendChild(row);
      });
    }

    function clearPackageInputs() {
      var inputs = document.querySelectorAll("#packages input");
      inputs.forEach(function(input) {
        input.value = "";
      });
    }

    function addContainer() {
      var containerTypeInput = document.querySelector("#containers .container-type-input");
      var containerQuantityInput = document.querySelector("#containers .container-quantity-input");
      var containerAttributeInput = document.querySelector("#containers .container-attribute-input");
      var containerDescriptionInput = document.querySelector("#containers .container-description-input");

      if (!containerTypeInput.value || !containerQuantityInput.value || !containerAttributeInput.value || !containerDescriptionInput.value) {
        alert("Please fill in all fields.");
        return;
      }

      var container = {
        containerType: containerTypeInput.value,
        containerQuantity: containerQuantityInput.value,
        containerAttribute: containerAttributeInput.value,
        containerDescription: containerDescriptionInput.value
      };

      containerList.push(container);
      renderContainersTable();
      clearContainerInputs();
    }

    function deleteContainer(index) {
      containerList.splice(index, 1);
      renderContainersTable();
    }

    function renderContainersTable() {
      var tableBody = document.getElementById("containersTableBody");
      tableBody.innerHTML = "";

      containerList.forEach(function(container, index) {
        var row = document.createElement("tr");
        var containerTypeCell = document.createElement("td");
        var containerQuantityCell = document.createElement("td");
        var containerAttributeCell = document.createElement("td");
        var containerDescriptionCell = document.createElement("td");
        var deleteCell = document.createElement("td");
        var deleteButton = document.createElement("button");

        containerTypeCell.textContent = container.containerType;
        containerQuantityCell.textContent = container.containerQuantity;
        containerAttributeCell.textContent = container.containerAttribute;
        containerDescriptionCell.textContent = container.containerDescription;

        deleteButton.textContent = "Delete";
        deleteButton.classList.add("delete-button");
        deleteButton.onclick = function() {
          deleteContainer(index);
        };

        deleteCell.appendChild(deleteButton);

        row.appendChild(containerTypeCell);
        row.appendChild(containerQuantityCell);
        row.appendChild(containerAttributeCell);
        row.appendChild(containerDescriptionCell);
        row.appendChild(deleteCell);

        tableBody.appendChild(row);
      });
    }

    function clearContainerInputs() {
      var inputs = document.querySelectorAll("#containers input");
      inputs.forEach(function(input) {
        input.value = "";
      });
    }
  </script>
 
</body>
</html>



fkaydet.php:

"<?php
// Check if the form was submitted using POST method
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    // Retrieve form data
  $shipperName = $_POST["shipper-name"];
    $shipperPhone = $_POST["shipper-phone"];
    $shipperAddress = $_POST["shipper-address"];
    $shipperEmail = $_POST["shipper-email"];

    $receiverName = $_POST["receiver-name"];
    $receiverPhone = $_POST["receiver-phone"];
    $receiverAddress = $_POST["receiver-address"];
    $receiverEmail = $_POST["receiver-email"];

    $shipmentType = $_POST["shipment-type"];
    $shipmentWeight = $_POST["shipment-weight"];
    $shipmentCourier = $_POST["shipment-courier"];
    $shipmentPackages = $_POST["shipment-packages"];
    $shipmentMode = $_POST["shipment-mode"];
    $shipmentProduct = $_POST["shipment-product"];
    $shipmentQuantity = $_POST["shipment-quantity"];
    $shipmentPayment = $_POST["shipment-payment"];
    $shipmentFreight = $_POST["shipment-freight"];
    $shipmentCarrier = $_POST["shipment-carrier"];
    $shipmentReference = $_POST["shipment-reference"];
    $shipmentDeparture = $_POST["shipment-departure"];
    $shipmentOrigin = $_POST["shipment-origin"];
    $shipmentDestination = $_POST["shipment-destination"];
    $shipmentPickupDate = $_POST["shipment-pickup-date"];
    $shipmentPickupTime = $_POST["shipment-pickup-time"];
    $shipmentDeliveryDate = $_POST["shipment-delivery-date"];
    $shipmentComments = $_POST["shipment-comments"];


$quantities = $_POST["qty"];
        
        $

       
$pieceTypes = $_POST["piece-type"];
        
       
$descriptions = $_POST["description"];
        
       
$lengths = $_POST["length"];
        
       
$widths = $_POST["width"];
        
       
$heights = $_POST["height"];
        
       
$weights = $_POST["weight"];

        


    // ... (The previous part of the code remains unchanged)

    // Connect to your MySQL database (replace placeholders with your actual database credentials)
    $servername = "localhost";
$username = "mil3dchippcomtr_cihandata";
$password = "Asmin/30";
$dbname = "mil3dchippcomtr_deneme";

    $conn = new mysqli($servername, $username, $password, $dbname);

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

    // Prepare and execute the SQL query to insert data into the database
    $sql = "INSERT INTO shipments (shipper_name, shipper_phone, shipper_address, shipper_email, receiver_name, receiver_phone, receiver_address, receiver_email, shipment_type, shipment_weight, shipment_courier, shipment_packages, shipment_mode, shipment_product, shipment_quantity, shipment_payment, shipment_freight, shipment_carrier, shipment_reference, shipment_departure, shipment_origin, shipment_destination, shipment_pickup_date, shipment_pickup_time, shipment_delivery_date, shipment_comments)
            VALUES ('$shipperName', '$shipperPhone', '$shipperAddress', '$shipperEmail', '$receiverName', '$receiverPhone', '$receiverAddress', '$receiverEmail', '$shipmentType', '$shipmentWeight', '$shipmentCourier', '$shipmentPackages', '$shipmentMode', '$shipmentProduct', '$shipmentQuantity', '$shipmentPayment', '$shipmentFreight', '$shipmentCarrier', '$shipmentReference', '$shipmentDeparture', '$shipmentOrigin', '$shipmentDestination', '$shipmentPickupDate', '$shipmentPickupTime', '$shipmentDeliveryDate', '$shipmentComments')";

    if ($conn->query($sql) === TRUE) {
        // Retrieve the auto-generated ID of the inserted shipment record
        $shipmentId = $conn->insert_id;

        // Loop through container data and insert into the database
      
if (isset($_POST['container-type']) && isset($_POST['container-quantity']) && isset($_POST['container-attribute']) && isset($_POST['container-description'])) {
        
        $

       
$containerTypes = $_POST['container-type'];
        
       
$containerQuantities = $_POST['container-quantity'];
        
       
$containerAttributes = $_POST['container-attribute'];
        
       
$containerDescriptions = $_POST['container-description'];

        

       


// Insert container data into the database
        
       
for ($i = 0; $i < count($containerTypes); $i++) {
            
           
$containerType = $conn->real_escape_string($containerTypes[$i]);
            
           
$containerQuantity = $conn->real_escape_string($containerQuantities[$i]);
            
           
$containerAttribute = $conn->real_escape_string($containerAttributes[$i]);
            
           
$containerDescription = $conn->real_escape_string($containerDescriptions[$i]);

            

           


// SQL query to insert container data into the database
            
           
$sql = "INSERT INTO containers (container_type, container_quantity, container_attribute, container_description, shipment_id)
                    VALUES ('$containerType', '$containerQuantity', '$containerAttribute', '$containerDescription', '$shipmentId')";

            

$conn->query($sql);
        }
    }

    
        }

        // Loop through package data and insert into the database
        for ($i = 0; $i < count($quantities); $i++) {
            $quantity = $quantities[$i];
            $pieceType = $pieceTypes[$i];
            $description = $descriptions[$i];
            $length = $lengths[$i];
            $width = $widths[$i];
            $height = $heights[$i];
            $weight = $weights[$i];

            $sql = "INSERT INTO packages (shipment_id, quantity, piece_type, description, length, width, height, weight)
                    VALUES ('$shipmentId', '$quantity', '$pieceType', '$description', '$length', '$width', '$height', '$weight')";

            if ($conn->query($sql) !== TRUE) {
                echo "Error: " . $sql . "<br>" . $conn->error;
            }
        }

        echo "Form data saved successfully!";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }

    $conn->close();
}
?>
" shipments tablosu na ekleniyor ama packages ve container bölümlerindeki tablolar eklenmiyor
Kullanıcı avatarı
TRWE_2012
Kayıtlı Kullanıcı
Mesajlar: 32
Kayıt: 14.05.2022, 06:59

Re: html formdaki tablo dizileri veritabanıındaki ilişkili tablolara aktarmıyor

Mesaj gönderen TRWE_2012 »

PHPBB forumu gibi bir sistemde, HTML form verilerini veritabanına aktarmak için birkaç adım izlemeniz gerekir. Eğer form verileri ilişkili tablolara aktarılmıyorsa, bu durum genellikle birkaç yaygın hatadan kaynaklanabilir.

1. Veritabanı Bağlantısını Kontrol Edin

Öncelikle, veritabanına bağlanıp bağlanmadığınızı kontrol edin. Aşağıdaki gibi bir bağlantı kodu kullanabilirsiniz:

Kod: Tümünü seç

$servername = "localhost";
$username = "kullanici_adiniz";
$password = "sifreniz";
$dbname = "veritabani_adiniz";

// Bağlantıyı oluştur
$conn = new mysqli($servername, $username, $password, $dbname);

// Bağlantıyı kontrol et
if ($conn->connect_error) {
    die("Bağlantı hatası: " . $conn->connect_error);
}
2. Form Verilerini Alın

HTML formunuzdan gelen verileri almak için $_POST veya $_GET süper globalini kullanmalısınız. Örneğin:

Kod: Tümünü seç

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $field1 = $_POST['field1'];
    $field2 = $_POST['field2'];
    // Diğer alanları da alabilirsiniz
}
3. Veritabanına Ekleme Sorgusunu Hazırlayın

Veritabanına eklemek için uygun SQL sorgusunu oluşturmalısınız. Eğer ilişkili tablolara veri eklemeniz gerekiyorsa, bu tablolardaki anahtarları da göz önünde bulundurmalısınız.

Kod: Tümünü seç

$sql = "INSERT INTO tablo_adi (field1, field2) VALUES ('$field1', '$field2')";

if ($conn->query($sql) === TRUE) {
    echo "Yeni kayıt başarıyla eklendi";
} else {
    echo "Hata: " . $sql . "<br>" . $conn->error;
}
4. İlişkili Tabloları Güncelleyin

Eğer form verileriniz birden fazla tabloya eklenmesi gerekiyorsa, her tablo için ayrı bir INSERT veya UPDATE sorgusu yazmalısınız. Örneğin:

Kod: Tümünü seç

// İlk tabloya veri ekle
$sql1 = "INSERT INTO tablo1 (field1) VALUES ('$field1')";
$conn->query($sql1);

// İkinci tabloya veri ekle
$last_id = $conn->insert_id; // İlk tablodaki son eklenen ID
$sql2 = "INSERT INTO tablo2 (foreign_key, field2) VALUES ('$last_id', '$field2')";
$conn->query($sql2);
5. Hata Kontrolü Yapın

Her sorgudan sonra hata kontrolü yaparak, hangi adımda sorun yaşandığını belirleyebilirsiniz. Örneğin:

Kod: Tümünü seç

if ($conn->query($sql) === FALSE) {
    echo "Hata: " . $conn->error;
}
6. Veritabanı Yapısını Kontrol Edin

Veritabanı yapınızın doğru olduğundan emin olun. İlişkili tablolar arasında doğru anahtar ilişkileri (foreign key) tanımlandığından emin olun.

Şimdi size yukarıda beş madde halinde parça parça anlatılanları tek bir kodlamada birleştirelim.Siz bu kodlama şablonuna göre gerekli ayarlamayı yapın kendiniz...

Örnek Form ve İşleme Kodu

Aşağıda basit bir örnek form ve bu formun işlenmesi için gerekli PHP kodu verilmiştir:

Form Kısmı :

Kod: Tümünü seç

<form method="post" action="islem.php">
    <input type="text" name="field1" placeholder="Field 1">
    <input type="text" name="field2" placeholder="Field 2">
    <input type="submit" value="Gönder">
</form>
PHP Kodu :

Kod: Tümünü seç

// islem.php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $field1 = $_POST['field1'];
    $field2 = $_POST['field2'];

    // Veritabanı bağlantısı
    $conn = new mysqli($servername, $username, $password, $dbname);

    // Hata kontrolü
    if ($conn->connect_error) {
        die("Bağlantı hatası: " . $conn->connect_error);
    }

    // İlk tabloya veri ekle
    $sql1 = "INSERT INTO tablo1 (field1) VALUES ('$field1')";

    if ($conn->query($sql1) === TRUE) {
        // İlk tablodaki son eklenen ID'yi al
        $last_id = $conn->insert_id;

        // İkinci tabloya veri ekle
        $sql2 = "INSERT INTO tablo2 (foreign_key, field2) VALUES ('$last_id', '$field2')";

        if ($conn->query($sql2) === TRUE) {
            echo "Veriler başarıyla eklendi.";
        } else {
            echo "İkinci tabloya ekleme hatası: " . $conn->error;
        }
    } else {
        echo "İlk tabloya ekleme hatası: " . $conn->error;
    }

    // Bağlantıyı kapat
    $conn->close();
}
Açıklamalar:

Veri Ekleme: İlk olarak, tablo1'e veri ekleniyor. Eğer bu işlem başarılı olursa, son eklenen kaydın ID'si $last_id değişkenine atanıyor.
İlişkili Tabloya Veri Ekleme: $last_id kullanılarak tablo2'ye veri ekleniyor. Bu, tablo1 ile tablo2 arasındaki ilişkiyi kurmak için gereklidir.
Hata Kontrolü: Her iki sorgudan sonra hata kontrolü yapılıyor. Eğer bir hata oluşursa, hata mesajı ekrana yazdırılıyor.
Bağlantıyı Kapatma: İşlem tamamlandıktan sonra veritabanı bağlantısı kapatılıyor.

Ekstra İpuçlar:

SQL Enjeksiyonuna Dikkat Edin: Yukarıdaki örnekte, kullanıcıdan alınan veriler doğrudan SQL sorgusuna ekleniyor. Bu, SQL enjeksiyonuna karşı savunmasızdır. Bunun önüne geçmek için, prepared statements kullanmanızı öneririm.

Örnek:

Kod: Tümünü seç

$stmt = $conn->prepare("INSERT INTO tablo1 (field1) VALUES (?)");
$stmt->bind_param("s", $field1);
$stmt->execute();


Veri Doğrulama: Kullanıcıdan alınan verileri doğrulamak ve temizlemek önemlidir. Bu, hem güvenlik hem de veri bütünlüğü açısından önemlidir.

PHPBB API Kullanımı: Forumun kendi API'sini veya fonksiyonlarını kullanarak veri eklemek daha iyi bir yaklaşım olabilir. Bu, forumun veri yapısını ve ilişkilerini korumanıza yardımcı olur.

Hata Ayıklama: Eğer hala sorun yaşıyorsanız, hata ayıklama için var_dump() veya print_r() gibi fonksiyonları kullanarak değişkenlerinizi kontrol edebilirsiniz.

Bu adımları takip ederek, HTML form verilerinizi veritabanındaki ilişkili tablolara başarıyla aktarabilirsiniz.
Cevapla

“PHP” sayfasına dön

Kimler çevrimiçi

Bu forumu görüntüleyen kullanıcılar: Hiç bir kayıtlı kullanıcı yok ve 4 misafir